Handler梯皿、Looper仇箱、MessageQueue源碼解析——MessageQueue



MessageQueue


/**
* Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
* You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/

Handler時(shí)用來發(fā)送消息的斟薇,調(diào)用sendMessageAtTime(),在調(diào)用MessageQueue的enqueueMessage(msg, uptimeMillis)方法恕酸,把消息插入到MessageQueue中奔垦。我們首先來看一下MessageQueue的enqueueMessage方法:

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

在Looper的loop()方法中,開啟了一個(gè)死循環(huán)尸疆,通過調(diào)用MessageQueue的next()方法,不斷的取出消息惶岭,再交給Handler去處理寿弱。

Message msg = queue.next();```

我們來看一下MessageQueue的next()方法:

    Message next() {
        //注釋1
        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;
                //注釋2
                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());
                }
                //注釋3
                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.
                //注釋4
                if (mQuitting) {
                    dispose();
                    return null;
                }

    }```

首先看注釋1:mPrt==0時(shí)返回一個(gè)null,mPrt在什么時(shí)候?yàn)榭漳匕丛睿⒁獾接幸粋€(gè)dispose()方法:

private void dispose() {
    if (mPtr != 0) {
        nativeDestroy(mPtr);
        mPtr = 0;
    }
}```

dispose()方法在哪調(diào)用呢症革,注意到在注釋4處,當(dāng)mQuitting==true時(shí)調(diào)用dispose()方法鸯旁。那么mQuitting在哪賦值為true呢:

    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

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

也就是上節(jié)我們說到調(diào)用Looper中的quit()獲得quitSafely()時(shí)會(huì)賦值為true噪矛,MessageQueue退出循環(huán)量蕊。

再看注釋3:Message是一個(gè)單向鏈表,next指向下一個(gè)Message艇挨。首先會(huì)先判斷當(dāng)前時(shí)間與Message的時(shí)間對(duì)比:

//獲取從開機(jī)到現(xiàn)在的時(shí)間
final long now = SystemClock.uptimeMillis();

when = SystemClock.uptimeMillis()+uptimeMillis;```

如果message已經(jīng)準(zhǔn)備好残炮,則返回一個(gè)Message對(duì)象,并把Message的next指針指向下一個(gè)message缩滨。

再看注釋2:什么時(shí)候message的target對(duì)象為空势就,在Handler發(fā)送Message時(shí)制定了target對(duì)象,當(dāng)message的target對(duì)象為空時(shí)說明不是由Handler插入進(jìn)來的脉漏,在MessageQueue的源碼中找到這樣一個(gè)方法苞冯;

    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;
        }
    }```
相當(dāng)于設(shè)置一個(gè)消息屏障,如果遇到一個(gè)消息屏障侧巨,就會(huì)不停的循環(huán)找到一個(gè)異步消息舅锄,一般我們使用的都是同步消息,我們可以通過Message的setAsynchronous(true)方法指定為異步消息司忱。

既然有開始循環(huán)皇忿,那么必定會(huì)有退出循環(huán),我們調(diào)用Looper的quit()或者quitSafely()方法時(shí)實(shí)際調(diào)用的是MessageQueue的quit方法烘贴。quit()和quitSafely()方法的區(qū)別在Looper中已經(jīng)提到了禁添,分別調(diào)用了
removeAllMessagesLocked()和removeAllFutureMessagesLocked()方法,現(xiàn)在我們來看一下具體實(shí)現(xiàn):

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

因?yàn)镸essage是一個(gè)單向鏈表桨踪,把所有的Message回收掉老翘。

   private void removeAllFutureMessagesLocked() {
       final long now = SystemClock.uptimeMillis();
       Message p = mMessages;
       if (p != null) {
           if (p.when > now) {
               removeAllMessagesLocked();
           } else {
               Message n;
               for (;;) {
                   n = p.next;
                   if (n == null) {
                       return;
                   }
                   if (n.when > now) {
                       break;
                   }
                   p = n;
               }
               p.next = null;
               do {
                   p = n;
                   n = p.next;
                   p.recycleUnchecked();
               } while (n != null);
           }
       }
   }```

當(dāng)p.when > now時(shí),即又延時(shí)的消息全部清空锻离,對(duì)于沒有延時(shí)的消息铺峭,通過一個(gè)死循環(huán)等待Handler處理完再回收。

我們注意到無論是Looper的loop()方法還是MessageQueue的next()方法汽纠,都是一個(gè)死循環(huán)卫键,那么為什么不會(huì)造成阻塞或者對(duì)CPU有什么消耗上的影響?請(qǐng)參考知乎大神回答:[Android中為什么主線程不會(huì)因?yàn)長ooper.loop()里的死循環(huán)卡死虱朵?](https://www.zhihu.com/question/34652589)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末莉炉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子碴犬,更是在濱河造成了極大的恐慌絮宁,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件服协,死亡現(xiàn)場離奇詭異绍昂,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門窘游,熙熙樓的掌柜王于貴愁眉苦臉地迎上來唠椭,“玉大人,你說我怎么就攤上這事忍饰√吧” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵喘批,是天一觀的道長撩荣。 經(jīng)常有香客問我,道長饶深,這世上最難降的妖魔是什么餐曹? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮敌厘,結(jié)果婚禮上台猴,老公的妹妹穿的比我還像新娘。我一直安慰自己俱两,他們只是感情好饱狂,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著宪彩,像睡著了一般休讳。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上尿孔,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天俊柔,我揣著相機(jī)與錄音,去河邊找鬼活合。 笑死雏婶,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的白指。 我是一名探鬼主播留晚,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼告嘲!你這毒婦竟也來了错维?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤橄唬,失蹤者是張志新(化名)和其女友劉穎赋焕,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體轧坎,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年泽示,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了缸血。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蜜氨。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖捎泻,靈堂內(nèi)的尸體忽然破棺而出飒炎,到底是詐尸還是另有隱情,我是刑警寧澤笆豁,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布郎汪,位于F島的核電站,受9級(jí)特大地震影響闯狱,放射性物質(zhì)發(fā)生泄漏煞赢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一哄孤、第九天 我趴在偏房一處隱蔽的房頂上張望照筑。 院中可真熱鬧,春花似錦瘦陈、人聲如沸凝危。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蛾默。三九已至,卻和暖如春捉貌,著一層夾襖步出監(jiān)牢的瞬間支鸡,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國打工昏翰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留苍匆,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓棚菊,卻偏偏與公主長得像浸踩,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子统求,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容