在日常開發中,需要延時任務的時候,往往會用到handler.postDelay()的方法,那麼一起來看看它的內部實現原理吧。
//Handler.java
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
在內部調用了sendMessageDelayed這個方法,而這個方法的返回值是布爾型,返回true表示這條消息已經被成功的放到了消息隊列,返回false表示這條消息添加失敗,在來看sendMessageDelayed方法的內部實現
//Handler.java
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
首先對時間做了一個格式化,並且在時間上做了一個當前時間和我們傳入的延時時間的和,而不是隻使用延時時間,接着直接返回sendMessageAtTime這個方法,這個方法的返回值表示的意思和上面一樣,是一系列的傳遞,再來看sendMessageAtTime方法
//Handler.java
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
這個方法對消息隊列做了一個判空,然後接着調用enqueueMessage方法
//handler.java
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
通過這一串方法的調用,實際上也就是將一條消息插入到了消息隊列裏。在來看具體的插入過程
MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
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) {
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;
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) { //1
nativeWake(mPtr);
}
}
return true;
}
可以用僞代碼簡化上面源碼的邏輯
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
//當延時時間小於當前鏈表頭到消息的執行時間
//插入的消息變爲消息頭
} else {
//延時比鏈表頭的時間要長
//用for循環尋找合適的時間節點
}
也就是說,延時消息會和當前消息隊列裏的消息頭的執行時間對比,如果比頭時間靠前,則會成爲新的消息頭,否則就依次遍歷,尋找合適的位置插入延時消息。
註釋1處的判斷也需要額外關注一下,通過needWake,找到了mBlocked這個變量
// Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
private boolean mBlocked;
這個變量是表明在執行next()
方法是否在等待一個有延時的消息而被阻塞。
//MessageQueue.java
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;
Message msg = mMessages;
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;
}
}
通過這段代碼,可以看出以下幾點
1.nativePollOnce(ptr,nextPollTimeoutMills)
會根據nextPollTimeoutMills的值確定是否休眠,如果nextPollTimeoutMills的>0,則next方法會在這裏休眠等待喚醒,這也解釋了爲什麼主線程裏的死循環爲什麼不會卡死,在主線程的MessageQueue沒有消息時,便阻塞在loop的queue.next()中的nativePollOnce()方法裏,此時主線程會釋放CPU資源進入休眠狀態,直到下個消息到達或者有事務發生,通過往pipe管道寫端寫入數據來喚醒主線程工作。這裏採用的epoll機制,是一種IO多路複用機制,可以同時監控多個描述符,當某個描述符就緒(讀或寫就緒),則立刻通知相應程序進行讀或寫操作,本質同步I/O,即讀寫是阻塞的。所以說,主線程大多數時候都是處於休眠狀態,並不會消耗大量CPU資。
2.從消息頭去消息會和當前時間做對比,如果需要延時,則計算延時時間,並賦值給nextPollTimeoutMills
3.如果不需要延時,則正常取出消息頭,並將mBlocked設置爲false
4.如果idleHandler數量爲0,則將mBlocked設置爲true。
最後,需要注意的是,Handler的Delay不一定會在when的時間執行
(1)在Loop.loop()中是順序處理消息,如果前一個消息處理耗時較長,完成之後已經超過了when,消息不可能在when時間點被處理。
(2)即使when的時間點沒有被處理其他消息所佔用,線程也有可能被調度失去cpu時間片。
(3)在等待時間點when的過程中有可能入隊處理時間更早的消息,會被優先處理,又增加了(1)的可能性。
所以由上述三點可知,Handler提供的指定處理時間的api諸如postDelayed()/postAtTime()/sendMessageDelayed()/sendMessageAtTime(),只能保證在指定時間之前不被執行,不能保證在指定時間點被執行。