Android多線程分析之四:MessageQueue的實現,
Android多線程分析之四:MessageQueue的實現
羅朝輝 (http://www.cnblogs.com/kesalin/)CC 許可,轉載請註明出處
在前面兩篇文章《Android多線程分析之二:Thread的實現》,《Android多線程分析之三:Handler,Looper的實現》中分別介紹了 Thread 的建立,運行,銷毀的過程以及 Thread與 Handler,Looper 之間的關聯:Thread 在其 run() 方法中建立和運行訊息處理迴圈 Looper,而 Looper::loop() 方法不斷地從 MessageQueue 中擷取訊息,並由 Handler 分發處理該訊息。接下來就來介紹 MessageQueue 的運作機制,MessageQueue。
參考源碼:
android/framework/base/core/java/android/os/MessageQueue.javaandroid/framework/base/core/java/android/os/Message.javaandroid/frameworks/base/core/jni/android_os_MessageQueue.handroid/frameworks/base/core/jni/android_os_MessageQueue.cpp
先來看 MessageQueue 的建構函式以及重要的成員變數:
// True if the message queue can be quit. private final boolean mQuitAllowed; private int mPtr; // used by native code Message mMessages; private boolean mQuiting; // Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout. 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: /* Gets the message queue's 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; // 訊息 idpublic int arg1; // 訊息參數public int arg2; // 訊息參數public Object obj; // 訊息參數long when; // 處理延遲時間,由 Handler 的 sendMessageDelayed/postDelayed 設定Handler target; // 處理訊息的 HandlerRunnable callback; // 處理訊息的回調Message next; // 鏈表結構,指向下一個訊息
Message 有一些名為 obtain 的靜態方法用於建立 Message,通常我們都是通過 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) { // 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; } } 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 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(mPtr, nextPollTimeoutMillis); synchronized (this) { if (mQuiting) { return null; } // 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 (false) Log.v("MessageQueue", "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // 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("MessageQueue", "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; } }
隊列被啟用之後,首先判斷隊首是不是訊息屏障,如果是則跳過所有的同步訊息,尋找最先要處理的非同步訊息。如果第一個待處理的訊息還沒有到要處理的時機則設定啟用等待時間;否則這個訊息就是需要處理的訊息,將該訊息設定為 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(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } msg.target.dispatchMessage(msg); msg.recycle(); } }
如果隊列中沒有訊息或者第一個待處理的訊息時機未到,且也沒有其他利用隊列空閑要處理的事務,則將隊列設定為設定 blocked 狀態,進入等待狀態;否則就利用隊列空閑處理其它事務。
至此,已經對 Android 多線程相關的主要概念 Thread, HandlerThread, Handler, Looper, Message, MessageQueue 作了一番介紹,下一篇就要講講 AsyncTask,這是為了簡化 UI 多線程編程為提供的一個便利工具類。
android中一個activiyt裡需要多次訪問服務讀取資料,需要開啟很多的線程,有什好的辦法處理這多線程
線程如果是一直啟動並執行,就檢測service是否已經啟動,啟動了就不開啟線程。每次開啟程式就啟動服務,線程也建立,建議看一下service的生命週期。。
在onStartCommand裡面建立線程,改成在onCreate裡面建就可以了
android訊息處理機制的問題 來解析一下
下面和大家分享一下android中非常重要的訊息處理機制,說到訊息處理,Message,MessageQueue,Looper,Handler這四個類的作用是我們必須要明白的。
下面分別談談他們的作用:
MessageQueue
MessageQueue表示訊息佇列,存放訊息的地方,按照“先進先出”的規則執行,每一個線程只可以擁有一個MessageQueue。當建立Looper對象的時候會建立一個MessageQueue對象。
Message
Message表示訊息對象,MessageQueue中存放的對象,一個MessageQueue中可以存放多個Message對象。通過調用Message類的obtain()方法或者調用Handler類的obtainMessage()方法擷取Message對象,但是這樣並不一定會建立一個新的Message對象,如果訊息池中有可用的Message對象則直接取出返回這個對象,否則如果訊息池中沒有可用的Message對象,則會建立一個新的Message對象。當訊息佇列中的Message對象被系統處理完之後,該Message對象會從MessageQueue中刪除,然後放入訊息池中。
Looper
Looper是用來操作MessageQueue的,每一個Looper對應一個MessageQueue,可以通過調用Looper.myLooper()方法擷取當前線程的Looper對象,Looper迴圈從MessageQueue中取出Message對象,交給Handler調用handleMessage方法進行處理,處理完之後Message對象被放入訊息池中。
Handler
Handler是訊息的處理者,Handler將需要傳遞的資訊封裝成Message對象,然後調用sendMessage方法將Message放入MessageQueue中,當MessageQueue迴圈到該Message時,調用相應Handler對象的handleMessage方法對其進行處理。 d-android.com/developer/
注意在UI線程也就是主線程中預設會建立Looper對象和MessageQueue對象,如果在我們自己新開的線程中要進行訊息處理,必須建立Looper對象和MessageQueue對象,通過調用Looper.prepare()方法可以建立Looper對象和MessageQueue對象,調用Looper.loop()方法可以啟動訊息迴圈隊列。
這裡 d-android.com/developer/thread-25343-1-1.html還有個例子,你可以參照一下,求給分啊!!!