編輯:關於 Android 程式設計
在前兩篇文章《Android 多線程剖析之二:Thread 的實現》與《Android 多線程剖析之三:Handler、Looper 的實現》中,我們分別介紹了 Thread 的創建、運行與銷毀過程,以及 Thread 與 Handler、Looper 之間的關聯:Thread 在其 run() 方法中創建並運行消息處理循環 Looper,而 Looper::loop() 則不斷從 MessageQueue 中取出消息,交由 Handler 分發處理。本文將接著剖析 MessageQueue 的運作機制。
參考源碼:
android/framework/base/core/java/android/os/MessageQueue.java android/framework/base/core/java/android/os/Message.java android/frameworks/base/core/jni/android_os_MessageQueue.h android/frameworks/base/core/jni/android_os_MessageQueue.cpp
先來看 MessageQueue 的構造函數以及幾個重要成員變量:
// 標識消息隊列是否允許退出 private final boolean mQuitAllowed; private int mPtr; // 供 native 代碼使用 Message mMessages; private boolean mQuiting; // 標識 next() 是否正阻塞在超時時間不為零的 pollOnce() 中 private boolean mBlocked;
mQuitAllowed:其含義與 Looper.prepare(boolean quitAllowed) 中的參數一致,表示是否允許中止;
mPtr:Android 的 MessageQueue 是通過調用 C++ native MessageQueue 來實現的,這個 mPtr 正是指向 native MessageQueue 的指針;
mMessages:由於 Message 採用鏈表結構,因此該變量代表整條 Message 鏈表;
mQuiting:標識是否已終止;
mBlocked:標識是否正在等待被激活以獲取消息。
MessageQueue 的構造函數非常簡單:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
nativeInit();
}
它通過轉調 native 方法 nativeInit() 來實現,後者定義在 android_os_MessageQueue.cpp 中:
static void android_os_MessageQueue_nativeInit(JNIEnv* env, jobject obj) {
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
if (!nativeMessageQueue) {
jniThrowRuntimeException(env, "Unable to allocate native queue");
return;
}
nativeMessageQueue->incStrong(env);
android_os_MessageQueue_setNativeMessageQueue(env, obj, nativeMessageQueue);
}
static void android_os_MessageQueue_setNativeMessageQueue(JNIEnv* env, jobject messageQueueObj, NativeMessageQueue* nativeMessageQueue) {
env->SetIntField(messageQueueObj, gMessageQueueClassInfo.mPtr,
reinterpret_cast<jint>(nativeMessageQueue));
}
nativeInit() 會創建一個 NativeMessageQueue 對象,並將該對象的指針賦給 Android MessageQueue 的 mPtr。NativeMessageQueue 的定義如下:
class MessageQueue : public RefBase {
public:
/* 獲取消息隊列所屬的 looper */
inline sp<Looper> getLooper() const { return mLooper; }
bool raiseAndClearException(JNIEnv* env, const char* msg);
virtual void raiseException(JNIEnv* env, const char* msg, jthrowable exceptionObj) = 0;
protected:
MessageQueue();
virtual ~MessageQueue();
protected:
sp<Looper> mLooper;
};
class NativeMessageQueue : public MessageQueue {
public:
NativeMessageQueue();
virtual ~NativeMessageQueue();
virtual void raiseException(JNIEnv* env, const char* msg, jthrowable exceptionObj);
void pollOnce(JNIEnv* env, int timeoutMillis);
void wake();
private:
bool mInCallback;
jthrowable mExceptionObj;
};
其中值得關注的是 NativeMessageQueue 的構造函數,以及 pollOnce、wake 兩個方法,它們正是 Java MessageQueue 中 nativePollOnce 與 nativeWake 的 native 實現:
NativeMessageQueue::NativeMessageQueue() : mInCallback(false), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {
mInCallback = true;
mLooper->pollOnce(timeoutMillis);
mInCallback = false;
}
void NativeMessageQueue::wake() {
mLooper->wake();
}
在 NativeMessageQueue 的構造函數中,它會獲取當前線程的 Looper(注意這是 C++ 的 Looper,定義在 frameworks/native/libs/utils/Looper.h 中),若當前線程尚未擁有 Looper,則創建一個並保存到線程的 TLS 中。pollOnce 與 wake 最終都是基於 Linux 的 epoll 模型實現的:pollOnce() 通過等待被激活,再從消息隊列中取出消息;wake() 則喚醒處於等待狀態的消息隊列,通知它有消息到達。這是典型的生產者-消費者模型。
對於 Android MessageQueue 而言,其主要職責就是接收投遞進來的消息,並取出下一個需要處理的消息。這兩項功能分別由 enqueueMessage() 和 next() 方法實現,其中 next() 在上一篇介紹 Looper.loop() 時已有提及。
在分析這兩個函數之前,先來認識一下 Message。前面說過,Message 是「完備」的,即它同時攜帶了消息內容以及處理消息的 Handler 或 callback。下面列出它的主要成員變量:
public int what; // 消息 id public int arg1; // 消息參數 public int arg2; // 消息參數 public Object obj; // 消息參數 long when; // 處理延遲時間,由 Handler 的 sendMessageDelayed/postDelayed 設置 Handler target; // 處理消息的 Handler Runnable callback; // 處理消息的回調 Message next; // 鏈表結構,指向下一個消息
Message 提供了一些名為 obtain 的靜態方法用於創建實例,通常我們會通過 Handler 的 obtain 靜態方法轉調 Message 的靜態方法來獲取新的 Message。
接下來分析 enqueueMessage:
final boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
boolean needWake;
synchronized (this) {
if (mQuiting) {
return false;
}
msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
// 新的隊首,若阻塞則喚醒事件隊列
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// 插入到隊列中間,通常無需喚醒,
// 除非隊首是消息屏障且當前消息是最早的異步消息
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; // 此時 p == prev.next
prev.next = msg;
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
首先它會檢測消息的合法性:是否正在使用中、是否有處理它的 Handler;隨後判斷 mQuiting 是否已中止。若未中止,則依據消息的處理時間,將其插入鏈表中合適的位置。這其中做了一些減少同步操作的優化:即便當前消息隊列已處於 Blocked 狀態,且隊首是一個消息屏障(與內存屏障的理念相似,這裡通過 p.target == null 來判斷隊首是否為消息屏障),也只有在要插入的消息是所有異步消息中最早需要處理的那條時,才會置 needWake 為真,去激活消息隊列以獲取下一個消息。
Handler 的 post/sendMessage 系列方法,最終都是通過轉調 MessageQueue 的 enqueueMessage 來實現的,例如:
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
其實 Handler 中與 Message 相關的靜態方法,都是通過 MessageQueue 對應的靜態方法來實現的,比如 removeMessages、hasMessages、hasCallbacks 等等,這裡不再逐一展開。至此,我們已經完整地梳理了如何通過 Handler 把消息提交到 MessageQueue 中。
下面來分析如何從 MessageQueue 中取出合適的消息,這是 next() 最主要的工作。next() 還承擔了一些其他職責,主要是為了提升系統效率,利用隊列空閒時通過 idle handler 完成一些瑣事,比如 GC 等。由於這部分與「獲取消息」關係不大,這裡從略。
final Message next() {
int pendingIdleHandlerCount = -1; // 僅在首次迭代時為 -1
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
if (mQuiting) {
return null;
}
// 嘗試取下一個消息,取到則返回
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// 被消息屏障阻擋,尋找下一條異步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// 下一個消息未到時機,設置喚醒超時
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 取到消息
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
msg.markInUse();
return msg;
}
} else {
// 沒有更多消息
nextPollTimeoutMillis = -1;
}
// 首次空閒時,獲取待執行的 idle handler 數量
if (pendingIdleHandlerCount < 0 &&
(mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// 沒有 idle handler 可執行,繼續等待
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// 執行 idle handler,僅在首次迭代時到達此處
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // 釋放對 handler 的引用
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// 將 idle handler 計數重置為 0,避免重復執行
pendingIdleHandlerCount = 0;
// 執行 idle handler 期間可能有新消息投遞,直接回頭再查一次而不等待
nextPollTimeoutMillis = 0;
}
}
隊列被激活之後,首先判斷隊首是否為消息屏障,若是則跳過所有同步消息,查找最先需要處理的異步消息。如果第一個待處理消息尚未到處理時機,則設置激活等待時間;否則該消息即為需要處理的消息,將其標記為 inuse,把隊列置於非 blocked 狀態,然後返回該消息。next() 在 Looper.loop() 中被調用,Looper 取到待處理消息後,便會調用與消息關聯的 Handler 來分發消息,這裡再回顧一下:
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(); // 可能阻塞
if (msg == null) {
// 沒有消息,表示消息隊列正在退出
return;
}
msg.target.dispatchMessage(msg);
msg.recycle();
}
}
如果隊列中沒有消息、或第一個待處理消息時機未到,且也沒有其他利用隊列空閒處理的事務,則將隊列置為 blocked 狀態進入等待;否則就利用這段空閒處理其他事務。
至此,我們已經對 Android 多線程相關的主要概念——Thread、HandlerThread、Handler、Looper、Message、MessageQueue 做了一番介紹。下一篇將講解 AsyncTask,它是為了簡化 UI 多線程編程而提供的一個便利工具類。
打造通用列表控件:告別每個列表都重寫一遍 Adapter
幾乎每個專案都有一堆列表頁。但仔細看,這些頁面彼此的差異其實只有兩點:子項佈局不同、點擊行為不同。剩下的下拉刷新、空資料提示、載入失敗重試、載入更多,幾乎每個列表都要重寫
Android 網絡變化實戰:用 Service 與廣播通知界面更新
先搞懂 Android 中的 Service Service 的分類可以從兩個維度來看。 按運行位置劃分:一是本地服務(Local Service),它依附在主進程上,並
安卓手機如何進入工程模式:一次搞懂隱藏測試入口
提到工程模式,很多非技術取向的使用者就頭痛。在一般人的印象裡,工程模式就是生硬的黑白畫面、整螢幕的英文和代碼指令,彷彿時光倒流回 DOS 時代,出於好奇想點進去,又怕一不
Android 入門必讀:從通信世代到你的第一個 App
一、先搞懂 1G、2G、3G、4G 到底在說什麼 我們常把行動網路講成「幾 G」,這個 G 其實是 Generation(世代)的縮寫,用來標示行動通訊技術的演進階段。從