Android Handler訊息機制原始碼解讀

瞌睡先生想睡覺發表於2018-06-06

這個東西在網上已經被很多人寫過了,自己也看過很多文章,大概因為自己比較愚笨一直對此不太理解,最近重新從原始碼的角度閱讀,並且配合著網上的一些相關部落格才算明白了一些

本文從原始碼的角度順著程式碼的執行去原始碼,限於作者的表達能力及技術水平,可能會有些問題,請耐心閱讀,如有不解或有誤的地方歡迎提出

從ActivityThread的入口去看

ActivityThread.class

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
        
        //這裡建立了屬於執行緒的Looper物件
        Looper.prepareMainLooper();
        
        //這裡建立了ActivityThread物件,隨之一起初始化的還有一個用於處理相應訊息的Handler物件
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        
        //在這裡開啟迴圈
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

這裡是App的入口,有著我們非常熟悉的main方法,
Looper.prepareMainLooper();這個方法建立了屬於主執行緒的Looper物件,並且將其放到了ThreadLocal中,再在Looper.loop();中取出Looper物件開啟迴圈

看下Looper.prepareMainLooper();方法的原始碼
Looper.class

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

    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));
    }
    
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }


prepareMainLooper()方法首先呼叫了prepare(false)方法,傳入的quitAllowed引數的意思是是否允許退出迴圈,主線是不允許的,其他的都是允許退出的,prepare方法首先要從sThreadLocal中get()一下判斷當前執行緒中是否已經有過Looper物件,如果已經有了就無法重複建立,如果沒有就初始化Looper物件然後放到sThreadLocal中去,sThreadLocal這個變數是ThreadLocal型別的,ThreadLocal這個類是用來儲存執行緒內的本地變數,或者是說,當前執行緒可以訪問的全域性變數,有興趣可以瞭解下原始碼,這裡就不說了.
Looper初始化的方法是私有的,所以只能通過prepare方法去建立,Looper初始化的時候順便初始化了MessageQueue物件和獲取了mThread這個當前執行緒的物件.然後prepare方法執行完成之後prepareMainLooper()方法還判斷了sMainLooper是否為空然後呼叫myLooper()方法取出放到sThreadLocal 中的Looper物件賦值給sMainLooper物件

所以根據上面的程式碼能得出結論,一個執行緒只有一個Looper物件,Looper物件中有一個MessageQueue物件

接下來看下Looper.loop()方法的原始碼:

Looper.class

    /**
     * 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();

        for (;;) {
            //從訊息佇列中取出訊息,可能會阻塞
            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 wasn't 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();
        }
    }

loop方法首先呼叫myLooper()方法來獲取當前執行緒存放在sThreadLocal中的Looper物件,然後進行一下非空判斷,在獲取到對應的
MessageQueue物件.然後來看關鍵程式碼:Message msg = queue.next(); 這句程式碼就是從訊息佇列裡面取出訊息,然後msg.target.dispatchMessage(msg);去分配給相應的Handler處理,msg.target是Message對應的Handler.
然後在呼叫msg.recycleUnchecked();對Message物件進行回收,等待再利用,如果next()取出的訊息為空就退出迴圈

接下來看queue.next();方法是如何將訊息取出來的
MessageQueue.class

    // True if the message queue can be quit.
    //是否允許退出,在初始化MessageQueue的時候傳入賦值
    private final boolean mQuitAllowed;

    @SuppressWarnings("unused")
    //這個屬性是有關底層c相關的東西,因為C相關的我也不會所以更底層的程式碼也沒看過,但是不影響去理解這個訊息機制
    private long mPtr; // used by native code
    
    //訊息佇列
    Message mMessages;
    //空閒時執行的程式碼
    private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
    private SparseArray<FileDescriptorRecord> mFileDescriptorRecords;
    private IdleHandler[] mPendingIdleHandlers;
    //是否退出
    private boolean mQuitting;

    // Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
    //是否阻塞
    private boolean mBlocked;


    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }


    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;
        }
        
        //這個值用於控制IdleHandler是否被執行
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            
            //這個是主要的阻塞方法,當訊息佇列中沒有時間或者需要執行的訊息沒到執行時間,就會阻塞,更底層是涉及到Linux的一些東西,我也不甚瞭解
            //nextPollTimeoutMillis這個引數是阻塞時間
            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());
                }
                //如果msg不為空
                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.
                    //沒有訊息為-1,無期限等待,直到有新訊息喚醒
                    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.
                //只有在上面沒有取到合適的訊息的時候才會執行到這一步,判斷pendingIdleHandlerCount是否小於0,只有小於0才會賦值,
                //小於0的情況只有在呼叫next方法進來的時候在迴圈體外面初始化
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                //經過上面的賦值,如果pendingIdleHandlerCount值小於等於0就不會執行下面的mIdleHandlers的相關程式碼
                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.
            //迴圈遍歷IdleHandler並執行,這裡的程式碼只有在沒有Message的時候才會執行
            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);
                }
                
                //false就會刪除掉
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            //這個引數賦值為0,就不會被重新賦值,所以沒呼叫一次next方法,IdleHandler中的程式碼最多隻會執行一次
            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;
        }
    }

至此迴圈去訊息的程式碼的邏輯差不多就這些,每次迴圈都會從MessageQueue中的Message中取出訊息,Message不僅僅是訊息的載體,它還是一個單連結串列結構,中間有一個next屬性指向下一個Message.還有就是mIdleHandlers,這個是用來在空閒時間,即在沒有取到合適執行的Message的時候回去檢測呼叫執行的程式碼,並且每次next只會執行一次,使用方法如下:

        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                //do something
                return false;
            }
        });

下面來從Handler入口來看下怎麼把訊息放到訊息佇列當中去

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                return false;
            }
        });

        handler.sendMessage(Message.obtain());

從Handler的初始化來引入:

Handler.calss

    final Looper mLooper;//Loper物件,如果不傳入則預設是本執行緒的Looper物件,如果為空則拋異常
    final MessageQueue mQueue;
    final Callback mCallback;
    final boolean mAsynchronous;//是否非同步,預設為false
    
    public Handler() {
        this(null, false);
    }
    
    public Handler(Callback callback) {
        this(callback, false);
    }

    public Handler(Looper looper) {
        this(looper, null, false);
    }
    
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

    public Handler(boolean async) {
        this(null, async);
    }
    
    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());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

在這裡可以看到,初始化的方法最終都是給Handler中的變數賦值

接下來是sendMessage方法:

Handler.class

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    
    ...
    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

sendMessage方法有很多過載的我就不都貼出了,但是他們最終呼叫的都是enqueueMessage方法,這個方法將Message繫結了當前的Handler,給Message設定了在Handler初始化的時候初始化的mAsynchronous引數,以及呼叫了MessageQueue物件的enqueueMessage方法,將Message物件和訊息執行時間傳入

enqueueMessage方法原始碼:
MessageQueue.class

	    boolean enqueueMessage(Message msg, long when) {
		//判斷Message繫結的Handler是否為空
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
		//判斷Message是否在使用中
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
		
		//同步程式碼塊
        synchronized (this) {
			
			//退出就回收Message,返回true
            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佇列
            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) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

這樣插入的程式碼也就說完了,整個流程的邏輯就是

Handler傳送Message到MessageQueue中,然後Looper不斷的迴圈從MessageQueue中取出Message再分配給相應的Handler執行

Looper: 負責不停的從MessageQueue中取出Message並且分配給Handler執行

MessageQueue: 負責Message佇列的讀和寫

Handler: Handler負責向MessageQueue中傳送Message並且處理Message

Meessage: 訊息載體

接下來看看前文中提到的一些方法:

在Looper中有呼叫的Handler.dispatchMessage()方法是怎麼處理訊息的
Handler.class:

	final Callback mCallback;
	
	//這個方法負責處理Message
    public void dispatchMessage(Message msg) {
		//首先判斷Message的 Runnable callback 是否為空
        if (msg.callback != null) {
			//不為空就執行callback的run方法
            handleCallback(msg);
        } else {
			//然後判斷mCallback是否為空,如果不為空就交給mCallback處理
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
			//如果上面兩個條件都不成立才呼叫本類的handleMessage方法
            handleMessage(msg);
        }
    }

    private static void handleCallback(Message message) {
        message.callback.run();
    }

再來看下Message的訊息回收機制
關於obtain方法,這個方法是用來獲取一個Message的,有很多過載的,我們只看最關鍵的
Message.class

    private static Message sPool;//Message用來放置被回收的Message
    private static int sPoolSize = 0;//當前sPool中訊息的數量

    private static final int MAX_POOL_SIZE = 50;//sPool內最大的訊息的數量
	
	
    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;
            }
        }
		//如果sPool中沒有Message就新建一個並返回
        return new Message();
    }
    
    
    public void recycle() {
		//正在使用的方法不允許回收
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
		//將訊息標記為正在使用狀態,然後清空其他的Message所附帶的訊息
        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) {
			//如果sPoolSize還沒到最大值就將訊息放到sPool中去
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

然後現在我們在回頭看下Message非同步的事情
Message.class 中有一個flags欄位,是用來記錄Message的是否正在使用中和訊息是否非同步的

    /*package*/ int flags;
    
    public boolean isAsynchronous() {
        return (flags & FLAG_ASYNCHRONOUS) != 0;
    }
    
    public void setAsynchronous(boolean async) {
        if (async) {
            flags |= FLAG_ASYNCHRONOUS;
        } else {
            flags &= ~FLAG_ASYNCHRONOUS;
        }
    }

    /*package*/ boolean isInUse() {
        return ((flags & FLAG_IN_USE) == FLAG_IN_USE);
    }

    /*package*/ void markInUse() {
        flags |= FLAG_IN_USE;
    }

是否正在使用中就不說了,下面主要來看看Message的Asynchronous的作用,根據上面的邏輯在一般情況下Message的Asynchronous的狀態並不影響訊息的分發機制,不過一旦遇到了msg的target為null的情況就會有影響,上面我們也看過了,在sendMessage的時候都會去繫結Handler那麼什麼時候出現target為null的情況呢,就是在呼叫了postSyncBarrier方法之後,這個方法在MessageQueue中,新增的這個特殊訊息的主要作用就是在在遇到這個訊息之後的同步Message都不會取到執行,非同步Message還是會繼續取出來執行這也是同步Message和非同步Message的區別

        if (msg != null && msg.target == null) {
            // 在這裡遇到這個同步障礙之後只會取非同步訊息
            do {
                prevMsg = msg;
                msg = msg.next;
            } while (msg != null && !msg.isAsynchronous());
        }

相關程式碼

    public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

    private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

			//找合適的位置插入
            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }


    public void removeSyncBarrier(int token) {
        // Remove a sync barrier token from the queue.
        // If the queue is no longer stalled by a barrier then wake it.
        synchronized (this) {
            Message prev = null;
            Message p = mMessages;
			//找到SyncBarrier
            while (p != null && (p.target != null || p.arg1 != token)) {
                prev = p;
                p = p.next;
            }
            if (p == null) {
                throw new IllegalStateException("The specified message queue synchronization "
                        + " barrier token has not been posted or has already been removed.");
            }
            final boolean needWake;
            if (prev != null) {
			    //如果在SyncBarrier之前還有訊息就不用喚醒
                prev.next = p.next;
                needWake = false;
            } else {
			    //如果SyncBarrier是第一個Message
                mMessages = p.next;
				//如果SyncBarrier移除後第一個訊息是空,或者繫結的Handler不為空,也就是說移除後的訊息不再是SyncBarrier也要喚醒
                needWake = mMessages == null || mMessages.target != null;
            }
            p.recycleUnchecked();

            // If the loop is quitting then it is already awake.
            // We can assume mPtr != 0 when mQuitting is false.
            if (needWake && !mQuitting) {
			    //需要喚醒且佇列沒有正在退出就喚醒
                nativeWake(mPtr);
            }
        }
    }

最後在多說一句,閱讀原始碼真的是一個讓人進步的有效方式,在過程中如果有不瞭解的可以去網上找一些別人閱讀原始碼的文章,對自己幫助很大,有時候感覺實在讀不下去,我都是硬著頭皮去看(╥﹏╥)

相關文章