異步消息處理線程的一般思路
要實現一個異步消息處理線程需要解決如下問題:
- 每個線程應該有一個消息隊列,用于對消息進行排隊
- 線程執行體中有一個無限的循環,不斷地從消息隊列中取出消息,并根據消息的來源,去調用相應的處理方法
- 其他線程可以給隊列添加消息
Android通過四個主要類來實現:
-
Message
封裝執行的方法或攜帶要處理的消息參數 -
MessageQueue
處理消息的排隊 -
Looper
不斷地從MessageQueue中取出消息派發給相應的處理器 -
Handler
通過它給MessageQueue發送Message,在其中執行相應的處理方法
Looper
一個Looper中持有一個MessageQueue對象,而一個線程只有一個Looper,這是怎么做到的呢?
先看Looper的構造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我們并不能自己創建Looper對象,而是通過Looper的靜態方法prepare
:
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
原來是通過線程局部變量來實現的,保證了一個線程只能有一個Looper。當Looper創建完了之后,就要開始消息隊列的循環了:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
可以看到,整個過程其實很簡單,調用MessageQueue的next
方法,取出消息隊列中的一個消息,然后調用其target
的dispatchMessageMessage
方法,最后回收消息。
Message
Message是一個攜帶信息的對象,一個Message可以攜帶以下東西:
-
int what
一般是用來表明該Message用處的標識 -
int arg1
和int arg2
兩個簡單的int值 -
Object obj
一個對象 -
Bundle data
一個Bundle對象,通過setData
方法設置
對于Message內部運行,有如下成員變量:
/*package*/ int flags; // Message的狀態
/*package*/ long when; // Message的執行時間
/*package*/ Handler target; // 處理該消息的Handler
/*package*/ Runnable callback; // 攜帶一個Runnable對象
// sometimes we store linked lists of these things
/*package*/ Message next; // 下一個Message
Message提供了一個public的構造方法,但并不建議我們直接使用,而是通過各種obtain
方法來獲取,因為Messge類本身維護了一個對象池,避免重復創建Message對象,它是怎么做到的呢?
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
可以看到sPool
就是這個池的頭指針,每次從Message鏈表中取出一個Message返回,然后指向下一個Message。而這個Message鏈表是在recycleUnckecked
方法中構建出來的:
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
回收完的Message插入到鏈表頭部,設計得太巧妙了!!!
Handler
對于一個Handler,通常我們有三種用法:
- 使用
sendXxx
去發送一個Message - 重寫
handleMessage
或者設置Callback
來處理發送給Handler的Message - 使用
postXxx
去異步執行一個Runnable
從上圖可以看到,其實各種postXxx
和sendXxx
最終都會調用到Handler的enqueueMessage
方法。比如postXxx
會把Runnable賦值給Message的callback
:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
而Handler的enqueueMessage
最終調用MessageQueue的enqueueMessage
:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
還記得Looper中的msg.target.dispatchMessage(msg);
嗎?Message中的target
就是與之關聯的Handler,dispatchMessage
的實現如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
如果這個Message帶的是一個Runnable,就直接調用run
方法了,否則交給Callback或自身的handlerMessage
去處理。
MessageQueue
MessageQueue的重要方法:
-
next
取出隊列中的下一個消息 -
enqueueMessage
將Message加入到消息隊列中 -
removeMessages
從隊列中移除Message
先看enqueueMessage
怎么實現:
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 (;;) { // 找到Message的插入位置
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;
}
其中的mMessage
相當于隊列的頭指針,而重點在于理解如何把Message插入到隊列中的合適位置。
next
方法很長,但做的事主要是去遍歷消息隊列,找出當前時間可以執行的Message。如隊列空了,就阻塞;如果下一個Message的執行時間還未到,則會等待nextPollTimeoutMillis
的時間再取出執行。
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 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;
}
}
// 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;
}
}
removeMessages
方法比較簡單,分為兩步處理:
- 移除消息頭中所有符合的Message,
mMessage
指針也要跟著移動。 - 遍歷剩下的消息隊列找出所有符合的Message,并移除。
以其中一個為例:
void removeMessages(Handler h, Runnable r, Object object) {
if (h == null || r == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.callback == r
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.callback == r
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}