MessageQuene
MessageQuene在Android中是消息隊(duì)列的意思,但內(nèi)部存儲(chǔ)結(jié)構(gòu)并不是隊(duì)列瞬欧,而是采用單向鏈表的數(shù)據(jù)結(jié)構(gòu)形式存儲(chǔ)消息呢铆。是Handler的具體實(shí)現(xiàn)之一(另外一個(gè)是Looper)筷畦。
MessageQuene#enqueueMessage()
enqueueMessage()是MessageQuene消息插入的實(shí)現(xiàn)方法,其實(shí)就是一個(gè)鏈表的插入操作。
boolean enqueueMessage(Message msg, long when) {
// 如果該消息沒有目標(biāo)handler
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
// 如果該消息正在使用中
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
// 如果隊(duì)列處于退出狀態(tài)
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
// 如果還有沒消息進(jìn)入或者延遲時(shí)間為0或者延遲時(shí)間小于上一個(gè)消息的延遲時(shí)間鳖宾,則進(jìn)入if判斷中
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
?1吼砂、當(dāng)?shù)谝粋€(gè)消息msg1插入時(shí),因?yàn)閙Messages為null鼎文,所以p也為null渔肩,接下來會(huì)進(jìn)入到if判斷里面。
?2拇惋、當(dāng)?shù)诙€(gè)消息msg2插入時(shí)周偎,假設(shè)msg2的延遲時(shí)間為0或者小于頭結(jié)點(diǎn)的延遲時(shí)間(即when = 0 || when < p.when)。
?3撑帖、當(dāng)后續(xù)消息插入時(shí)蓉坎,假設(shè)延時(shí)時(shí)間不為0并且延時(shí)時(shí)間不小于頭結(jié)點(diǎn)的延時(shí)時(shí)間(即不滿足when = 0 || when < p.when),則會(huì)進(jìn)入到else判斷中執(zhí)行下面這段代碼胡嘿。
for (;;) {
// 上一個(gè)節(jié)點(diǎn)
prev = p;
// 下一個(gè)節(jié)點(diǎn)(即上一個(gè)節(jié)點(diǎn)的后面一個(gè)節(jié)點(diǎn))
p = p.next;
// 表示已經(jīng)遍歷完成或者當(dāng)前被插入的消息的延遲時(shí)間小于當(dāng)前被遍歷到的消息的延遲時(shí)間
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 把msg插入prev節(jié)點(diǎn)和p節(jié)點(diǎn)之間
msg.next = p; // invariant: p == prev.next
prev.next = msg;
首先會(huì)進(jìn)入無限循環(huán)蛉艾,結(jié)束循環(huán)的條件是p == null || when < p.when(即已經(jīng)遍歷到消息鏈表的最后一個(gè)節(jié)點(diǎn)或者當(dāng)前被插入的消息的延遲時(shí)間小于當(dāng)前被遍歷到的消息的延遲時(shí)間)。結(jié)束循環(huán)后會(huì)把msg插入prev節(jié)點(diǎn)和p節(jié)點(diǎn)之間衷敌。
總結(jié)
由上面分析可以看出mMessages始終充當(dāng)?shù)氖窍㈡湵淼念^結(jié)點(diǎn)勿侯。當(dāng)沒有消息或者消息延時(shí)時(shí)間為0或者消息的延時(shí)時(shí)間比頭結(jié)點(diǎn)的延時(shí)時(shí)間短時(shí)都采用的是鏈表頭插的方式。其他時(shí)候是通過比較延遲時(shí)間缴罗,按照延遲時(shí)間長短順序插入(延遲時(shí)間越短越靠前助琐,會(huì)被優(yōu)先處理)。
MessageQuene#next()
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
// 取出頭結(jié)點(diǎn)
Message msg = mMessages;
// 消息不為空并且沒有目標(biāo)Handler
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
next()方法比較簡單面氓,就是從頭結(jié)點(diǎn)開始兵钮,無限循環(huán)消息鏈表,一直取消息舌界,有消息便會(huì)返回這條消息交給Looper處理并從消息鏈表中移除這條消息掘譬,沒有就會(huì)一直阻塞在這里。因?yàn)橐话闱闆r下msg.target不為null(即目標(biāo)Handler不為null)禀横,所以會(huì)進(jìn)入到if (msg != null)判斷中屁药。并且執(zhí)行下面的程序:
// 由上面代碼得知prevMsg = null
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
// 因?yàn)閙Messages始終是頭結(jié)點(diǎn),把mMessages指向頭結(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)柏锄,
// 就相當(dāng)于移除了頭結(jié)點(diǎn)(即是移除了將被返回的消息)
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
// 標(biāo)記正在使用
msg.markInUse();
// 返回msg
return msg;
因?yàn)橄⑹前凑請(qǐng)?zhí)行的先后順序插入的(優(yōu)化被執(zhí)行的排在前面)酿箭,所以取消息的從頭結(jié)點(diǎn)開始取。