Android多線程之Handler、Looper與MessageQueue源碼解析

本文的目的是來分析一下Android系統中以Handler、Looper、MessageQueue組成的異步消息處理機制,經過源碼來了解一下整個消息處理流程的走向以及相關三者之間的關係。app

須要先了解如下幾個預備知識less

  • Handler: UI線程或子線程經過Handler向MeessageQueue(消息隊列)發送Message
  • MessgaeQueue: 經過Handlerd發送的消息並不是是當即執行的,須要存入一個消息隊列中依次來執行
  • Looper: Looper不斷從MessageQueue中獲取消息並將之傳遞給消息處理者(便是消息發送者Handler自己)進行處理
  • 互斥機制:可能會有多條線程(1條UI線程,N條子線程)向同一個消息隊列插入消息,此時就須要進行同步

Handler發送消息的形式主要有如下幾個形式,其最終調用的都是sendMessageAtTime()方法異步

public final boolean sendMessage(Message msg){
        return sendMessageDelayed(msg,0);
    }
    
    
   public final boolean post(Runable r){
        return sendMessageDelayed(getPostMessage(r),0);
    }
    
    
   public final boolean sendMessageDelayed(Message msg ,long delayMillis){
        if(delayMillis<0){
            delayMillis = 0 ;
        }
        return sendMessageAtTime(msg,SystemClock.uptimeMillis()+delayMillis);
   }

能夠看到sendMessageAtTime()方法中須要一個已初始化的MessageQueue類型的全局變量mQueue,不然程序沒法繼續走下去async

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);
    }

而mQueue變量是在構造函數中進行初始化的,且mQueue是成員變量,這說明Handler與MessageQueue是一一對應的關係,不可更改ide

若是構造函數沒有傳入Looper函數,則會默認使用當前線程關聯的Looper對象,mQueue須要依賴從Looper對象中獲取, 若是Looper對象爲null,則會直接拋出異常,且從異常信息 Can't create handler inside thread that has not called Looper.prepare() 中能夠看到,在向 Handler 發送消息前,須要先調用 Looper.prepare()函數

public Handler (Callback callback,boolean async){
    
        ...
        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 ;
    
    }

走進Looper類中,能夠看到,myLooper()方法是從sThreadLocal 對象中獲取Looper對象的,sThreadLocal對象又是經過prepare(boolean)來進行賦值的,且該方法只容許調用一次,一個線程只能建立一個Looper對象,不然將拋出異常oop

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    
     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));
    }

此處除了由於prepare(boolean)屢次調用會拋出異常致使沒法關聯多個Looper外,Looper類的構造函數也是私有的,且在構造函數中還初始化了一個線程常量mThread,這都說明了Looper只能關聯到一個線程,且關聯以後不能改變post

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

那麼Looper.prepare(boolean) 方法又是在哪裏調用呢?查找該方法的全部引用,能夠發如今Looper類中有以下方法, 從名字來看,能夠猜想該方法是由主線程來調用的。 查找其引用ui

public static void prepareMainLooper(){
        prepare(false);
        synchronized(Looper.class){
            if(sMainLooper !=null){
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

最後定位到ActivityThread 類的main()方法this

看到main()函數的方法簽名, 能夠知道該方法就是一個應用的起始點,即當應用啓動時,系統就自動爲咱們在主線程作好了Handler的初始化操做,所以在主線程裏咱們能夠直接使用Handler

若是是在子線程中建立Handler, 則須要咱們手動調用Looper.prepare()方法

public static void main(String[] args){
        
        ...
        Looper.prepareMainLooper();
        
        ActivityThread thread = new ActivityThread();
        thread.attch(flase);
        
        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");
    }

回到最開始, 既然Looper對象已由系統來爲咱們初始好了, 那咱們就能夠從中獲得mQueue對象

public Handler(Callback callback, boolean async) {
        ···
        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;
    }

mQueue 又是在Looper類的構造函數中初始化的, 且mQueue是Looper類的成員變量, 這說明Looper與MessageQueue是一一對應的關係

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

sendMessgaeAtTime()方法中在處理Message時,最終調用的是enqueueMessage()方法

當中,須要注意msg.target = this 這句代碼,target對象指向了發送消息的主體,即Handler對象自己,即由Handler對象發送MessageQueue 的消息最後仍是要交由Handler對象自己來處理

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) {
        //target 對象指向的也是發送消息的主體,即 Handler 對象
        //即由 Handler 對象發給 MessageQueue 的消息最後仍是要交由 Handler 對象自己來處理
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

由於存在多個線程往同一個Loop線程的MessageQueue中插入消息的可能, 因此enqueueMessgae()內部須要進行同步。能夠看出MessageQueue內部是以鏈表的結構來存儲Message的(Meassage.next),根據Message的延時時間的長短來將決定其在消息隊列中的位置

mMessages表明的是消息隊列中的第一條消息,若是mMessages爲空, 說明消息隊列是空的,或者mMessages的觸發時間要比新消息晚,則將新消息插入消息隊列的頭部,若是mMessgaes不爲空,則尋找消息隊列中第一條觸發時間比新消息晚 的非空消息,並將新消息插到該消息前面

到此,一個按照處理時間進行排序的消息隊列就完成了,後邊要作的就是從消息隊列中依次取出消息進行處理了

boolean enqueueMessage(Message msg, long when) {
        //Message 必須有處理者
        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 (;;) {
                    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並回調給Handler的

在MessageQueue中消息的讀取實際上是經過內部的next()方法進行的,next()方法是一個無限循環的方法, 若是消息隊列中沒有消息,則該方法會一直阻塞,當有新消息來的時候next()方法會返回這條消息並將其從單鏈表中刪除

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;
        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;
                }

                // 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;
        }
    }

next()方法又是經過Looper類的Loop()方法來循環調用的,而loop()方法也是一個無限循環,惟一跳出循環的條件就是queue.next()方法返回爲null, loop()方法就是在ActiityThread的main()函數中調用的

由於next()方法是一個阻塞操做, 因此當沒有消息也會致使loop()方法一直阻塞着,而當MessageQueue中有了新的消息,Looper就會及時處理這條消息並調用Message.target.dispatchMessage(Message) 方法將消息傳回給 Handler 進行處理

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

看下Handler對象處理消息的方法

/**
    * Handler system messages here .
    */
    public void dispatchMessage(Message msg){
    
        if(msg.callback!=null){
            handleCallback(msg);
        }else{
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    
    }

若是msg.callback 不爲空,則調用callback對象的run()方法,該callback實際上就是一個Runnable對象,對應的是Handler對象的post()方法

private static void handleCallback(Message message){
        message.callback.run();
    }
    
    public final boolean post(Runnable r){
        return sendMessageDelayed(getPostMessage(r),0);
    }
    
    private static Message getPostMessage(Runnable r){
        Message m = Message.obtain();
        m.callback = r ;
        
        return m ;
    
    }

若是mCallback 不爲null ,則經過該接口來回調處理消息, 若是在初始化Handler對象時沒有經過構造函數傳入Callback回調接口, 則交由handleMessage(Message)方法來處理消息,咱們通常也是經過重寫Handler的hanleMessage(Message)方法來處理消息

最後來總結下以上的內容

1、在建立Handler實列時要麼爲構造函數提供一個Looper實列,要麼默認使用當前線程關聯的Looper對象,若是當前線程沒有關聯的Looper對象,則會致使拋出異常

2、Looper與Thread ,Looper與MessageQueue都是一一對應的關係, 在關聯後沒法更改,但Handler 與Looper能夠是多對一的關係

3、Handler能用於更新UI有個前提條件:Handler與主線程關聯在了一塊兒。 在主線程中初始化的Handler會默認與主線程綁定在一塊兒, 因此此後在處理Message時,handleMessage(Message msg)方法的所在線程就是主線程,由於Handler能用於更新UI

4、能夠建立關聯到另外一個線程Looper的Handler,只要本線程可以拿到另一個線程的Looper實列

new Thread("Thread_1") {
            @Override
            public void run() {
                Looper.prepare();
                final Looper looper = Looper.myLooper();
                new Thread("Thread_2") {
                    @Override
                    public void run() {
                        Handler handler = new Handler(looper);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                //輸出結果是:Thread_1
                                Log.e(TAG, Thread.currentThread().getName());
                            }
                        });
                    }
                }.start();
                Looper.loop();
            }
        }.start();
相關文章
相關標籤/搜索