Android Handler機制8之消息的取出與消息的其他操作

Android Handler機制系列文章整體內容如下:

本片文章的主要內容如下:

  • 1、消息的取出
  • 2、消息(Message)的移除
  • 3、關閉消息隊列
  • 4、查看消息是否存在
  • 5、阻塞非安全執行

一、消息的取出

(一)、消息的取出主要是通過Looper的loop方法

代碼如下Looper.java 122行

  /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
         //第1步
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //第2步
        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();

         //第3步
        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 traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                // 第5步
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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);
            }
            // 第6步
            msg.recycleUnchecked();
        }
    }

這個方法已經在Android Handler機制4之Looper與Handler簡介中說過了,我就重點說下流程,大體上分為6步

  • 第1步 獲取Looper對象
  • 第2步 獲取MessageQueue消息隊列對象
  • 第3步 while()死循環遍歷
  • 第4步 通過queue.next()來從MessageQueue的消息隊列中獲取一個Message msg對象
  • 第5步 通過msg.target. dispatchMessage(msg)來處理消息
  • 第6步 通過msg.recycleUnchecked()方來回收Message到消息對象池中

由于第1步第2步第3步比較簡單就不講解了,而第6步y已經講解過,也不講解了,下面我們來重點說下第4步第5步

(二)、Message next()方法

從消息隊列中提取Message交給Looper來處,這個步驟應該是MessageQueue乃至整個線程消息機制的核心了,所以我們將這部分放到最后來將,因為其內部的代碼邏輯比較復雜,涉及到了障柵如何攔截同步消息、如何阻塞線程、如何在空閑的時候執行IdleHandler以及如何關閉Looper等內容,在源碼已經做了詳細的注釋,不過由于邏輯比較復雜所以想要看明白,大家還要花費一定時間的。

PS:在Looper.loop()中獲取消息的方式就是調用next()方法。

代碼在MessageQueue.java
307行

    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.
        // 如果消息循環已經退出了。則直接在這里return。因為調用disposed()方法后mPtr=0
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        //記錄空閑時處理的IdlerHandler的數量
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        // native層用到的變量 ,如果消息尚未到達處理時間,則表示為距離該消息處理事件的總時長,
        // 表明Native Looper只需要block到消息需要處理的時間就行了。 所以nextPollTimeoutMillis>0表示還有消息待處理
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                //刷新下Binder命令,一般在阻塞前調用
                Binder.flushPendingCommands();
            }
            // 調用native層進行消息標示,nextPollTimeoutMillis 為0立即返回,為-1則阻塞等待。
            nativePollOnce(ptr, nextPollTimeoutMillis);
            //加上同步鎖
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                // 獲取開機到現在的時間
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                // 獲取MessageQueue的鏈表表頭的第一個元素
                Message msg = mMessages;
                 // 判斷Message是否是障柵,如果是則執行循環,攔截所有同步消息,直到取到第一個異步消息為止
                if (msg != null && msg.target == null) {
                     // 如果能進入這個if,則表面MessageQueue的第一個元素就是障柵(barrier)
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    // 循環遍歷出第一個異步消息,這段代碼可以看出障柵會攔截所有同步消息
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                       //如果msg==null或者msg是異步消息則退出循環,msg==null則意味著已經循環結束
                    } while (msg != null && !msg.isAsynchronous());
                }
                 // 判斷是否有可執行的Message
                if (msg != null) {  
                    // 判斷該Mesage是否到了被執行的時間。
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        // 當Message還沒有到被執行時間的時候,記錄下一次要執行的Message的時間點
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Message的被執行時間已到
                        // Got a message.
                        // 從隊列中取出該Message,并重新構建原來隊列的鏈接
                        // 刺客說明說有消息,所以不能阻塞
                        mBlocked = false;
                        // 如果還有上一個元素
                        if (prevMsg != null) {
                            //上一個元素的next(越過自己)直接指向下一個元素
                            prevMsg.next = msg.next;
                        } else {
                           //如果沒有上一個元素,則說明是消息隊列中的頭元素,直接讓第二個元素變成頭元素
                            mMessages = msg.next;
                        }
                        // 因為要取出msg,所以msg的next不能指向鏈表的任何元素,所以next要置為null
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        // 標記該Message為正處于使用狀態,然后返回Message
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    // 沒有任何可執行的Message,重置時間
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                // 關閉消息隊列,返回null,通知Looper停止循環
                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.
                // 當第一次循環的時候才會在空閑的時候去執行IdleHandler,從代碼可以看出所謂的空閑狀態
                // 指的就是當隊列中沒有任何可執行的Message,這里的可執行有兩要求,
                // 即該Message不會被障柵攔截,且Message.when到達了執行時間點
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                
                // 這里是消息隊列阻塞( 死循環) 的重點,消息隊列在阻塞的標示是消息隊列中沒有任何消息,
                // 并且所有的 IdleHandler 都已經執行過一次了
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
    
                // 初始化要被執行的IdleHandler,最少4個
                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,并且根據返回值判斷是否保留IdleHandler
            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.
            // 重點代碼,IdleHandler只會在消息隊列阻塞之前執行一次,執行之后改標示設置為0,
            // 之后就不會再執行,一直到下一次調用MessageQueue.next() 方法。
            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.
            // 當執行了IdleHandler 的 處理之后,會消耗一段時間,這時候消息隊列里的可能有消息已經到達 
             // 可執行時間,所以重置該變量回去重新檢查消息隊列。
            nextPollTimeoutMillis = 0;
        }
    }

總的來說當我們試圖產品從MessageQueue中獲取一個Message的時候,會分為以下幾步

  • 首先、MessageQueue會先判斷隊列中是否有障柵的存在,如果有的話,只會返回異步消息,否則就逐個返回。
  • 其次、當MessageQueue沒有任何消息可以處理的時候,它會進度阻塞狀態等待新的消息到來(無線循環),在阻塞之前它會執行以便 IdleHandler,所謂的阻塞其實就是不斷的循環查看是否有新的消息進入隊列中。
  • 再次、當MessageQueue被關閉的時候,其成員變量mQuitting會被標記為true,然后在Looper視圖從隊列中取出Message的時候返回null,而Message==null就是告訴Looper消息隊列已經關閉,應該停止循環了,這一點可以在Looper.loop()房源中看出。
  • 最后、如果大家細心一定會發現,Handler線程里面實際上有兩個無線循環體,Looper循環體和MessageQueue循環體,真正阻塞的地方是MessageQueue的next()方法里。

這里有個難點,我簡單說下

//****************  第一部分  ***************
                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;
                }
  • 第一種情況:第一部分主要是判斷鏈表的第一個元素是否是障柵,如果是障柵,則進入if,內部區域,然后進行while循環,如果在鏈表中有一個元素是異步的,則跳出循環,然后進入第二部分,其中第二部分就是取出這個異步消息
  • 第二種情況:沒進入進入第一部分的if,則說明頭部元素不是障柵(barrier),則直接進入第二部分,這時候取出的就是當前的頭部元素。

PS:

nativePollOnce是阻塞操作,其中nextPollTimeoutMillis代表下一個消息到來前,需要等待的時長,當nextPollTimeoutMillis=-1時,表示消息隊列無消息,會一直等待下去。nativePollOnce()是在native做了大量的工作。

(三)、msg.target.dispatchMessage(msg);方法

我們知道這個方法其實是Handler的dispatchMessage(Message)方法,那我們就來詳細看下
代碼在Handler.java 93行

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //當Message存在回調方法,回調msg.callback.run()方法;
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //當Handler存在Callback成員變量時,回調方法handleMessage();
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //Handler自身的回調方法handleMessage()
            handleMessage(msg);
        }
    }

這個方法很簡單就是二個條件,三種情況

  • 情況1:如果msg.callback 不為空,則執行handleCallback(Message),而handleCallback(Message)的內部最終調用的是message.callback.run();,所以最終是msg.callback.run()。
  • 情況2:如果msg.callback 為空,且mCallback不為空,則執行mCallback.handleMessage(msg)。
  • 情況3:如果msg.callback 為空,且mCallback也為空,則執行handleMessage()方法

這里我們可以看到,在分發消息時三個方法的優先級分別如下:

  • Message的回調方法優先級最高,即message.callback.run();
  • Handler的回調方法優先級次之,即Handler.mCallback.handleMessage(msg);
  • Handler的默認方法優先級最低,即Handler.handleMessage(msg)。

對于很多情況下,消息分發后的處理情況是第3種情況,即Handler.handleMessage(),一般地往往是通過覆寫該方法從而實現自己的業務邏輯。

二、消息(Message)的移除

(一) Handler的消息移除

消息(Message)的移除,其實就是根據身份what、消息Runnable或msg.obj移除隊列中對應的消息。例如發送msg,用同一個msg.what作為參數。所有方法最終調用MessageQueue.removeMessages,來進行時機操作的。

代碼如下,因為不復雜,我就合并在一起了

// Handler.java
public final void removeCallbacks(Runnable r) {
    mQueue.removeMessages(this, r, null);
}

public final void removeCallbacks(Runnable r, Object token) {
    mQueue.removeMessages(this, r, token);
}

public final void removeMessages(int what) {
    mQueue.removeMessages(this, what, null);
}

public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

所以我們知道,Handler里面的刪除工作,其實本地都是調用MessageQueue來操作的。

下面我們就來看下MessageQueue是怎么操作的?

(二) MessageQueue的消息移除

MessageQueue的消息移除在其類類的方法如下:


MessageQueue的消息移除.png

一共有5個方法如下:

  • 移除方法1:void removeMessages(Handler , int , Object )
  • 移除方法2:void removeMessages(Handler, Runnable,Object)
  • 移除方法3:void removeCallbacksAndMessages(Handler, Object)
  • 移除方法4:void removeAllMessagesLocked()
  • 移除方法5:void removeAllFutureMessagesLocked()

那我們就依次講解下:

移除方法1:void removeMessages(Handler , int , Object )方法

從消息隊列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 587行

  void removeMessages(Handler h, int what, Object object) {
        // 第1步
        if (h == null) {
            return;
        }
         // 第2步
        synchronized (this) {
           // 第3步
            Message p = mMessages;

            // Remove all messages at front.

          
            //第4步
            while (p != null && p.target == h && p.what == what
                   && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            //第5步
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && n.what == what
                        && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

上面的代碼大體可以分為5個步驟如下:

  • 第1步、,對傳遞進來的Handler做非空判斷,如果傳遞進來的Handler為空,則直接返回
  • 第2步、,加同步鎖
  • 第3步、,獲取消息隊列鏈表的頭元素
  • 第4步、,如果從消息隊列的頭部就有符合刪除條件的Message,就從頭開始遍歷刪除所有符合條件的Message,并不端更新mMessages指向的Message。
  • 第5步、,因為有了第4步、,前面的的情況不會發生,也就是我們不需要關心指向的問題,現在處理的問題就是刪除剩下的符合刪除條件的Message。

總結一下:

從消息隊列中刪除Message的操作也是遍歷消息隊列然后刪除所有符合條件的Message,但是這里有連個小細節需要注意,從代碼中可以看出刪除Message分為兩次操作,第一次是先判斷符合刪除條件的Message是不是從消息隊列的頭部就開始有了,這時候會設計修改mMessage指向的問題,而mMessage代表的就是整個消息隊列,在排除了第一種情況之后,剩下的就是繼續遍歷隊列刪除剩余的符合刪除條件的Message。其他重載方法也是同樣的操作,唯一條件就是條件不同而已,

移除方法2:void removeMessages(Handler, Runnable,Object)方法

從消息隊列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 604行


    void removeMessages(Handler h, Runnable r, Object object) {
        if (h == null || r == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h && p.callback == r
                   && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && n.callback == r
                        && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

里面代碼和移除方法1:void removeMessages(Handler , int , Object )基本一致,唯一不同就是篩選條件不同而已。

移除方法3:void removeMessages(Handler, Runnable,Object)方法

從消息隊列中刪除所有符合指定條件的Message

代碼在MessageQueue.java 689行

    void removeCallbacksAndMessages(Handler h, Object object) {
        if (h == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h
                    && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

里面代碼和移除方法1:void removeMessages(Handler , int , Object )基本一致,唯一不同就是篩選條件不同而已。

移除方法4:void removeAllMessagesLocked()方法

刪除所有的消息

代碼在MessageQueue.java 722行

   private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

這個方法很簡單,就是刪除所有的消息

移除方法5:void removeAllFutureMessagesLocked()

刪除所有未來消息

代碼在MessageQueue.java 732行

    private void removeAllFutureMessagesLocked() {
         // 第1步
        final long now = SystemClock.uptimeMillis();
         // 第2步
        Message p = mMessages;
        if (p != null) {
            // 第3步
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                // 第4步
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
               // 第5步
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }

這個方法大體上分為5個步驟,具體解釋如下:

  • 第1步:獲取當前時間(其實從手機開機到現在的時間)
  • 第2步:獲取消息隊列鏈表的的頭元素
  • 第3步:如果頭元素的執行的時間就大于當前時間,因為我們知道鏈表的排序其實有從當前到未來的順序排列的,所以但如果頭元素大于當前時間,意味著這個鏈表的所有元素的執行時間都大于當前,則刪除鏈表中的全部元素。
  • 第4步:如果消息隊列中的頭元素小于或等于當前時間,則說明要從消息隊列中截取,從中間的某個未知的位置截取到消息隊列鏈表的隊尾。這個時候就需要找到這個具體的位置,這個步驟主要就是做這個事情。通過對比時間,找到合適的位置
  • 第5步:找到合適的位置后,就開始刪除這個位置到消息隊列隊尾的所有元素

三、關閉消息隊列

通過前面的文章,我們知道Handler消息機制的停止,本質上是停止Looper的循環,在Android Handler機制4之Looper與Handler簡介文章中我們知道Looper的停止實際上是關閉消息隊列的關閉,現在我們來揭示MessageQueue是如何關閉的

代碼在MessageQueue.java 413行

    void quit(boolean safe) {
         // 第1步
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }
        // 第2步
        synchronized (this) {
            // 第3步
            if (mQuitting) {
                return;
            }
            mQuitting = true;
            // 第4步
            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            // 第5步
            nativeWake(mPtr);
        }
    }

這個方法內部大概分為5個步驟

  • 第1步:判斷是否允許退出,因為在構造MessageQueue對象的時候傳入了一個boolean參數,來表示該MessageQueue是否允許退出。而這個boolean參數在Looper里面設置,Loooper.prepare()方法里面是true,在Looper.prepareMainLooper()是false,由此可見我們知道:主線程的MessageQueue是不能退出。其他工作線程的MessageQueue是可以退出的。
  • 第2步:加上同步鎖
  • 第3步:主要防止重復退出,加入一個mQuitting變量表示是否退出
  • 第4步:如果該方法的變量safe為true,則刪除以當前時間為分界線,刪除未來的所有消息,如果該方法的變量safe為false,則刪除當前消息隊列的所有消息。
  • 第5步:刪除小時后nativeWake函數,以觸發nativePollOnce函數,結束等待,這個塊內容請在Android Handler機制9之Native的實現中,這里就不詳細描述了

四、查看消息是否存在

Handler機制也存在查找是否存在某條消息的機制,代碼如下:

// Handler.java
public final boolean hasMessages(int what) {
    return mQueue.hasMessages(this, what, null);
}

public final boolean hasMessages(int what, Object object) {
    return mQueue.hasMessages(this, what, object);
}

public final boolean hasCallbacks(Runnable r) {
    return mQueue.hasMessages(this, r, null);
}

我們發現其內部都是調用MessageQueue的hasMessages函數,那我們就來看下

(一) boolean hasMessages(Handler h, int what, Object object) 方法

代碼在MessageQueue.java 587行

    boolean hasMessages(Handler h, int what, Object object) {
        //第1步
        if (h == null) {
            return false;
        }
        //第2步
        synchronized (this) {
            //第3步
            Message p = mMessages;
            //第4步
            while (p != null) {
                if (p.target == h && p.what == what && (object == null || p.obj == object)) {
                    return true;
                }
                p = p.next;
            }
            return false;
        }
    }

該方法的主要內容可以分為4個步驟

  • 第1步:判斷傳入進來的Handler是否為空,如果傳入的Handler為空,直接返回false,表示沒有找到
  • 第2步:加上同步鎖
  • 第3步:取出消息隊列鏈表中的頭部元素
  • 第4步:遍歷消息隊里鏈表中的所有元素,如果有元素消息符合指定條件則return false,如果遍歷完畢還沒有則返回false

boolean hasMessages(Handler h, Runnable r, Object object)方法和本方法基本一致,唯一不同就是篩選條件不同而已。我就說講解了。

五、阻塞非安全執行

如果當前執行線程是Handler的線程,Runnable會被立刻執行。否則把它放在消息隊列中一直等待執行完畢或者超時,超時后這個任務還在隊列中,在后面的某個時刻它仍然會執行,很有可能造成死鎖,所以盡量不要用它。

這個方法使用場景是Android初始化一個WindowManagerService,應為WindowManagerService不成功,其他組件就不允許繼續,所以使用阻塞的方式直到完成。
代碼在Handler.java 461行


    /**
     * Runs the specified task synchronously.
     * <p>
     * If the current thread is the same as the handler thread, then the runnable
     * runs immediately without being enqueued.  Otherwise, posts the runnable
     * to the handler and waits for it to complete before returning.
     * </p><p>
     * This method is dangerous!  Improper use can result in deadlocks.
     * Never call this method while any locks are held or use it in a
     * possibly re-entrant manner.
     * </p><p>
     * This method is occasionally useful in situations where a background thread
     * must synchronously await completion of a task that must run on the
     * handler's thread.  However, this problem is often a symptom of bad design.
     * Consider improving the design (if possible) before resorting to this method.
     * </p><p>
     * One example of where you might want to use this method is when you just
     * set up a Handler thread and need to perform some initialization steps on
     * it before continuing execution.
     * </p><p>
     * If timeout occurs then this method returns <code>false</code> but the runnable
     * will remain posted on the handler and may already be in progress or
     * complete at a later time.
     * </p><p>
     * When using this method, be sure to use {@link Looper#quitSafely} when
     * quitting the looper.  Otherwise {@link #runWithScissors} may hang indefinitely.
     * (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
     * </p>
     *
     * @param r The Runnable that will be executed synchronously.
     * @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
     *
     * @return Returns true if the Runnable was successfully executed.
     *         Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @hide This method is prone to abuse and should probably not be in the API.
     * If we ever do make it part of the API, we might want to rename it to something
     * less funny like runUnsafe().
     */
    public final boolean runWithScissors(final Runnable r, long timeout) {
         // 第1步
        if (r == null) {
            throw new IllegalArgumentException("runnable must not be null");
        }
         // 第2步
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout must be non-negative");
        }

          // 第3步
         // 如果為同一個線程,則直接執行runnable,而不需要加入到消息隊列。
        if (Looper.myLooper() == mLooper) {
            r.run();
            return true;
        }
 
        // 第4步
        BlockingRunnable br = new BlockingRunnable(r);
        return br.postAndWait(this, timeout);
    }

首先先簡單翻譯一下注釋:

  • 同步運行指定的任務。
  • 如果當前線程就是Handler的處理線程,則可以不用排隊,直接運行這個runnable。否則如果當前線程和Handler的處理編程不是同一個線程則需要發送這個runnable到Handler線程,并且等待它完成后再返回。
  • 使用這個方法是有風險的,使用不當可能會導致死鎖。不要在有鎖或者可能有鎖的代碼區域調用這個方法。
  • 這個方法的使用場景通常是,一個后臺線程必須等待Handler線程中的一個任務的完成。但是,這往往是不優雅設計才會出現的問題。所以在使用這個方法的時候,請首先考慮改進設計方案。
  • 這個方法的使用場景是:在你建立Handler線程之前,你需要執行一些初始化操作。
  • 如果發生超時,雖然該方法還是會返回false,但是該
    如果超時發生,那么該方法返回<code> false </ code>,但是runnable仍是會保留在Handler中,并且在一段時間以后會在被執行。
  • 在使用這個方法的時候,并且要退出一個Looper的時候,請一定要調用quitSafely()這個方法。否則runWithScissors()這個方法可能會無限期掛起。(TODO:我們應該通知MessageQueue去阻止runnable來解決這個問題)

該方法內部的執行流程主要分為4個步驟,如下:

  • 第1步、:Runnable非空判斷
  • 第2步、:timeout是否小于0判斷
  • 第3步、:如果Looper的線程和Handler的線程是同一個線程
  • 第4步、,構造一個BlockingRunnable對象,并調用該對象的postAndWait(Handler,long)方法

上面涉及到一個咱們之前沒有講解過的類:BlockingRunnable,他是Handler的靜態內部類,我們來研究下

(一)、Handler的靜態內部類BlockingRunnable

BlockingRunnable是Handler的一個私有內部靜態類,利用Object的wait和notifyAll方法實現。

代碼在Handler.java

  private static final class BlockingRunnable implements Runnable {
        private final Runnable mTask;
        private boolean mDone;

        public BlockingRunnable(Runnable task) {
            mTask = task;
        }

        @Override
        public void run() {
            try {
                mTask.run();
            } finally {
                synchronized (this) {
                    mDone = true;
                     // runnable 執行完之后,會通知wait的線程不再wait
                    notifyAll();
                }
            }
        }

        public boolean postAndWait(Handler handler, long timeout) {
            if (!handler.post(this)) {
                return false;
            }

            synchronized (this) {
                if (timeout > 0) {
                    final long expirationTime = SystemClock.uptimeMillis() + timeout;
                    while (!mDone) {
                        long delay = expirationTime - SystemClock.uptimeMillis();
                        if (delay <= 0) {
                            return false; // timeout
                        }
                       // post runnable 之后,將調用線程變為wait狀態
                        try {
                            wait(delay);
                        } catch (InterruptedException ex) {
                        }
                    }
                } else {
                    while (!mDone) {
                         // post runnable 之后,將調用線程變為wait狀態
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            }
            return true;
        }
    }

通過分析源碼我們獲取的了如下信息:

  • 1、該類實現了Runnable接口
  • 2、構造函數:接受一個Runnable作為參數的構造函數,包含了真正要執行的Task。
  • 3、run函數很簡單,直接調用mTask.run(),一個finally內會同步對象本身(因為mDone涉及到多線程,而notifyAll()則需要synchronized配合)
  • 4、postAndWait(Handler, long):首先嘗試將BlockingRunnable自己post到handler上,如果post失敗,則直接返回false;其次如果上一步的post成功,就需要同步對象本身(為了使用wait());此時,如果timeout>0,那么就一個while循環+wait(long),中間有任何的interrupt都直接catch重新結算wait的時間,只有在任務完成(mDone=true,另外線程的run函數會設置此值)或者任何超時才會返回(true/false);如果imeout <=0,也就無限等待了
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,182評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,489評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,290評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,776評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,510評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,866評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,860評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,036評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,585評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,331評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,536評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,058評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,754評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,154評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,469評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,273評論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,505評論 2 379

推薦閱讀更多精彩內容