Andorid 執行緒間通訊Handler原理(原始碼解析)
*class LooperThread extends Thread { *public Handler mHandler; * *public void run() *//1.建立當前執行緒的Looper,初始化函式會同時建立MessageQueue *Looper.prepare(); *//2.建立當前執行緒的Handler,處理髮送來的訊息。 *mHandler = new Handler() { *public void handleMessage(Message msg) { *// process incoming messages here *} *}; *//3.Looper開啟迴圈,不斷訪問是否有新的訊息 *Looper.loop(); *} 複製程式碼
//4.在任意執行緒傳送一個訊息 mHandler.sendMessage(msg); 複製程式碼
Looper的建立和儲存
Looper.prepare() 建立當前執行緒的Looper。Looper初始化函式會同時建立當前執行緒的MessageQueue。Looper建立完成儲存到ThreadLocal裡。
Looper.java
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ 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"); } //ThreadLocal儲存Looper物件,每個執行緒都有自己的Looper。ThreadLocal內部會區分不同執行緒進行儲存,每個執行緒有獨立的map, Looper的存取是存放在當前執行緒的map裡面的 sThreadLocal.set(new Looper(quitAllowed)); } 複製程式碼
Looper.java
Looper初始化函式會同時建立當前執行緒的MessageQueue
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } 複製程式碼
ThreadLocal存取Looper
簡介:以執行緒為維度,可以拿到當前執行緒的map,進行資料儲存。這裡存放的是當前執行緒的Looper物件。
ThreadLocal.jva
/** * Sets the current thread's copy of this thread-local variable * to the specified value.Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of *this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); //拿到當前執行緒的map. 所以不同執行緒呼叫,獲取到的是不同map ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } /** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @paramt the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; } /** * Returns the value in the current thread's copy of this * thread-local variable.If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() { Thread t = Thread.currentThread(); //從當前執行緒在後去map,從map裡面去取值(這裡最終從map獲取的是當前執行緒的Looper) ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } 複製程式碼
Handler傳送訊息
Handler簡介:傳送訊息(建立Handler的執行緒或者其他執行緒)和處理訊息(建立Handler的執行緒)
Handler.java
Handler初始化
///Handler的初始化,拿到當前的Looper和MessageQueue public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } //獲取當前執行緒的Looper mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } //獲取當前執行緒的MessageQueue mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } 複製程式碼
Looper.java
獲取當前的執行緒已經建立的Looper.
/** * Return the Looper object associated with the current thread.Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); } 複製程式碼
Handler.java
mHandler.sendMessage();傳送訊息
/** * Pushes a message onto the end of the message queue after all pending messages * before the current time. It will be received in {@link #handleMessage}, * in the thread attached to this handler. * * @return Returns true if the message was successfully placed in to the *message queue.Returns false on failure, usually because the *looper processing the message queue is exiting. */ public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } /** * Enqueue a message into the message queue after all pending messages * before (current time + delayMillis). You will receive it in * {@link #handleMessage}, in the thread attached to this handler. * * @return Returns true if the message was successfully placed in to the *message queue.Returns false on failure, usually because the *looper processing the message queue is exiting.Note that a *result of true does not mean the message will be processed -- if *the looper is quit before the delivery time of the message *occurs then the message will be dropped. */ public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } /** * Enqueue a message into the message queue after all pending messages * before the absolute time (in milliseconds) <var>uptimeMillis</var>. * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b> * Time spent in deep sleep will add an additional delay to execution. * You will receive it in {@link #handleMessage}, in the thread attached * to this handler. * * @param uptimeMillis The absolute time at which the message should be *delivered, using the *{@link android.os.SystemClock#uptimeMillis} time-base. * * @return Returns true if the message was successfully placed in to the *message queue.Returns false on failure, usually because the *looper processing the message queue is exiting.Note that a *result of true does not mean the message will be processed -- if *the looper is quit before the delivery time of the message *occurs then the message will be dropped. */ 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); } //Handler傳送訊息,最後其實是放入到了建立Handler執行緒對應的MessageQueue裡面 return queue.enqueueMessage(msg, uptimeMillis); } 複製程式碼
MessageQueue 儲存和獲取訊息
MessageQueue 簡介:負責執行緒的訊息管理,內部儲存Message使用連結串列資料結構
MessageQueue.java
//向MessageQueue 放入一條訊息 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 do not 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; } //從MessageQueue獲取一條訊息 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; //獲取訊息可能是阻塞的,會一直迴圈等待新的訊息。Looper.loop(); 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(); //返回從連結串列裡獲取到的Message 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; } } 複製程式碼
Looper.loop()如何分發訊息
Looper進行無限迴圈,如果從MessageQueue獲取到訊息,則回撥到Handler的handleMessage(msg)去處理
Looper.java
Looper.loop()後都做做了什麼?
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ 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; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); //進行無限迴圈,從MessageQueue中獲取資料 for (;;) { //從MessageQueue中獲取Message,如果當前MessageQueue裡面沒有訊息,next()方法是阻塞的。 Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { //獲取到Message則分發到Handler進行處理 msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread was not corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } } 複製程式碼
Handler.java
/** * Handle system messages here. */ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //4.回撥Handler的handleMessage(); 完整的訊息分發至此完成。 handleMessage(msg); } } 複製程式碼
Q&A
- looper.loop()方法是阻塞的,主執行緒為什麼還可以執行其他函式(Activity生命週期回撥等等)?
通過主執行緒的handler傳送Message到主執行緒MessageQueue。Looper.loop()獲取到Message,然後回撥handler.handleMessage()方法去執行各種事件回撥(Activity生命週期回撥等等)。詳細自行檢視ActivityThread.java類。 複製程式碼
- 執行緒間通訊Handler核心點在哪裡?
生產者(Handler任意執行緒生產)消費者(建立Looper執行緒消費)模式 複製程式碼