Handler源碼分析

Handler機(jī)制算是個(gè)老生常談的問題了裹赴,最近又看了下源碼,決定還是形成文字記錄下來靠譜诀浪。

1棋返、handler

handler在Android用于不同線程間的通信。使用時(shí)雷猪,一般會(huì)在主線程(接收消息的線程)new一個(gè)handler睛竣,那就先看下handler的源碼:

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

從該構(gòu)造方法可以得到以下幾個(gè)信息:
1、Handler對(duì)象依賴于Looper對(duì)象求摇。
2射沟、Looper對(duì)象中當(dāng)中持有mQueue對(duì)象。
3与境、Looper中的mQueue對(duì)象賦給了Handler成員變量验夯。
3、Looper.prepare()用來創(chuàng)建Looper對(duì)象摔刁,有了Looper對(duì)象后才能創(chuàng)建Handler挥转。
這里引出了Looper這個(gè)概念,讓我們看下Looper是什么吧共屈。

2绑谣、Looper

Looper的創(chuàng)建,即上面提到的Looper.prepare()方法:

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

Looper的獲绒忠:

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() {
        return sThreadLocal.get();//從ThreadLocal中獲取
    }

Looper的構(gòu)造方法:

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

該構(gòu)造函數(shù)為私有的借宵,也就是說Looper只能由它的靜態(tài)方法prepare創(chuàng)建。構(gòu)造方法內(nèi)創(chuàng)建了MessageQueue對(duì)象矾削。

那么Looper又是什么呢壤玫,它有啥用豁护?看下源碼的注釋:

Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
{@link #prepare} in the thread that is to run the loop, and then
{@link #loop} to have it process messages until the loop is stopped.

簡(jiǎn)單的說明下Looper是用來和Thread綁定的,它的內(nèi)部維護(hù)了一個(gè)消息隊(duì)列mQueue垦细,所有發(fā)送給Thread的消息都會(huì)進(jìn)入這個(gè)隊(duì)列择镇,然后Looper會(huì)循環(huán)處理這些消息。
看到這里括改,我們會(huì)有幾個(gè)疑問:
1、Looper的創(chuàng)建和獲取方法中引入了sThreadLocal家坎,這是什么嘱能?
2、Looper如何與Thread綁定的虱疏?
3惹骂、Looper是如何接收消息,如何將消息存入它內(nèi)部的消息隊(duì)列mQueue的做瞪?
4对粪、Looper是如何處理消息的?
下面就帶著這幾個(gè)疑問装蓬,依次解決著拭。

3、ThreadLocal

首先講下handler的作用牍帚,當(dāng)然相信大家都懂得:假設(shè)有兩個(gè)線程MainThread和SubThread儡遮。SubThread中通過獲取在MainThread中創(chuàng)建的Handler對(duì)象,調(diào)用Handler的post或sendMessage方法暗赶,將消息傳遞給MainThread后并在該線程中處理鄙币。
由上面對(duì)Looper的介紹,我們又知道蹂随,實(shí)質(zhì)上十嘿,發(fā)送的消息,最終交給了與MainThread綁定的Looper對(duì)象中的mQueue隊(duì)列岳锁。最終的消息處理也是由這個(gè)Looper調(diào)度的绩衷。
如果讓我們自己設(shè)計(jì)這樣一個(gè)功能,不難想到浸锨,如果一個(gè)Looper綁定了多個(gè)Thread唇聘,那么Looper在接收到消息后處理,該在哪個(gè)線程中執(zhí)行呢柱搜?所以每個(gè)Looper對(duì)象應(yīng)只綁定一個(gè)線程迟郎,即每個(gè)Looper都是被某個(gè)線程獨(dú)占的。
事實(shí)上源碼就是這么設(shè)計(jì)聪蘸,且每個(gè)Thread中只有一個(gè)Looper對(duì)象宪肖。
源碼中為了保證每個(gè)Thread都有它獨(dú)立的Looper表制,采用了ThreadLocal

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

用中文概括下來講控乾,就是對(duì)于同一類型的對(duì)象傳給ThreadLocal后么介,ThreadLocal提供了一個(gè)綁定策略,它會(huì)將該對(duì)象綁定至當(dāng)前的線程中蜕衡,最終使得每個(gè)Thread中該類型的對(duì)象都是獨(dú)立的壤短,互不影響。
如果不太了解的話慨仿,可以參考這篇文章:http://www.reibang.com/p/95291228aff7久脯,看下文章開頭的示例大概就明白了。
用在這里镰吆,就是ThreadLocal能夠讓每個(gè)Thread中都擁有獨(dú)立的Looper對(duì)象帘撰。ThreadLocal是怎樣實(shí)現(xiàn)這一魔法的,看源碼:
Looper內(nèi)持有靜態(tài)且final的sThreadLocal成員變量万皿。

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

在prepare方法中摧找,創(chuàng)建新的Looper對(duì)象,并傳給sThreadLocal牢硅。

sThreadLocal.set(new Looper(quitAllowed));

ThreadLocal中:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //this蹬耘,本類對(duì)象,如果結(jié)合Looper源碼唤衫,這里的this就是指sThreadLocal婆赠。
            map.set(this, value);
        else
            createMap(t, value);
    }

   ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

從源碼可以看出,set方法內(nèi)首先獲取當(dāng)前Thread內(nèi)的ThreadLocalMap佳励,如果不存在休里,就先創(chuàng)建。到Thread源碼內(nèi)驗(yàn)證一下赃承,果然有個(gè)ThreadLocal.ThreadLocalMap類型的threadLocals 成員變量妙黍。從名字xxxMap可以看出,這個(gè)成員變量是以鍵值對(duì)形式存儲(chǔ)數(shù)據(jù)的瞧剖。
結(jié)合Looper源碼拭嫁,key即為sThreadLocal,value即為L(zhǎng)ooper對(duì)象抓于。這樣做粤,對(duì)于每個(gè)Thread線程,就都會(huì)有它獨(dú)立的Looper對(duì)象了捉撮。
到這里怕品,上面提到的四個(gè)問題中1和2就解決了。

4巾遭、MessageQueue

MessageQueue是在Looper的構(gòu)造方法內(nèi)初始化的肉康,Thread和Looper是唯一綁定的闯估,所以每個(gè)Thread也只能有唯一的一個(gè)MessageQueue!MessageQueue是鏈表解構(gòu)的隊(duì)列吼和,因?yàn)橄⑿枰l繁的增刪涨薪,所以采用鏈表效率更高。
當(dāng)我們調(diào)用Handler的sendMessage或post發(fā)送一個(gè)消息時(shí)炫乓,最終都會(huì)調(diào)用:

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

這里的queue就是在Looper構(gòu)造函數(shù)內(nèi)初始化的那個(gè)刚夺。
消息存入該鏈表后,Looper的loop方法就會(huì)循環(huán)遍歷這個(gè)鏈表末捣,一次取出消息光督,最后交給Handler的handleMessage取處理:

    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();
        //無限循環(huán),遍歷消息鏈表
        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 {
                //msg.target就是發(fā)送消息時(shí)的那個(gè)handler塔粒。
                //最終調(diào)用handler的handleMessage方法處理。
                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);
            }

            msg.recycleUnchecked();
        }
    }

Looper的loop方法筐摘,會(huì)在創(chuàng)建Looper(Handler)的那個(gè)線程中調(diào)用卒茬,該方法中最關(guān)鍵的是msg.target.dispatchMessage(msg);,target從何而來咖熟?看下Handler的enqueueMessage方法:

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

原來msg.target就是發(fā)送消息的那個(gè)Handler本身圃酵!事件回傳給Handler的dispatchMessage處理,貼出源碼:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

是不是熟悉的方法來了馍管!如果msg是runnable事件郭赐,調(diào)用handleCallback(msg),最終調(diào)用runnable的run方法執(zhí)行确沸;
如果msg是普通事件捌锭,就調(diào)用 handleMessage(msg)執(zhí)行,而handleMessage不就是我們通常會(huì)重寫的handler的方法嗎罗捎?
同時(shí)观谦,因?yàn)閘oop方法在創(chuàng)建Looper的線程中執(zhí)行,那么loop方法中的所有方法調(diào)用桨菜,都未涉及到線程切換豁状,所以也都在Looper創(chuàng)建的線程中執(zhí)行。

5倒得、畫個(gè)圖吧

想了想還是來個(gè)圖直觀點(diǎn)泻红!


handler原理.png

6、總結(jié)

Handler這一套機(jī)制霞掺,說白了也挺簡(jiǎn)單的谊路。
1、首先需要調(diào)用Looper.prepare()根悼,為當(dāng)前線程創(chuàng)建Looper對(duì)象凶异,同時(shí)創(chuàng)建的還有MessageQueue蜀撑,ThreadLocal會(huì)用來保證每個(gè)線程擁有獨(dú)立的一套Looper和MessageQueue。
2剩彬、然后再new Handler()酷麦,它會(huì)持有剛才在線程中創(chuàng)建的Looper和MessageQueue對(duì)象,從而與線程間接關(guān)聯(lián)喉恋。(注意沃饶,一個(gè)Handler對(duì)應(yīng)一個(gè)線程,但一個(gè)線程中可以有多個(gè)Handler轻黑,但多個(gè)handler多會(huì)持有同一個(gè)Looper和MessageQueue對(duì)象)糊肤。
3、最后在同樣的線程中調(diào)用Looper.loop()循環(huán)遍歷MessageQueue鏈表氓鄙,該循環(huán)是一個(gè)阻塞方法馆揉,它會(huì)一直執(zhí)行,當(dāng)消息到來抖拦,就會(huì)依次取出消息升酣,讓后讓發(fā)送該消息的那個(gè)handler處理事件(具體怎么處理取決于我們重寫的Handler的handleMessage方法)。由于Looper.loop()方法是在創(chuàng)建Looper的那個(gè)線程中調(diào)用的态罪,所以handleMessage也會(huì)在同一線程中執(zhí)行噩茄。
4、Handler的異步消息處理機(jī)制的關(guān)鍵在于:Handler對(duì)象對(duì)每個(gè)線程都是可見的复颈,在不同線程中绩聘,可以拿到這個(gè)handler發(fā)送消息;但Handler對(duì)應(yīng)的Looper和MessageQueue卻是每個(gè)線程獨(dú)立存在的耗啦;消息最終會(huì)在創(chuàng)建Looper的那個(gè)線程中被處理凿菩,從而達(dá)到異步處理的目的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末芹彬,一起剝皮案震驚了整個(gè)濱河市蓄髓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌舒帮,老刑警劉巖会喝,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異玩郊,居然都是意外死亡肢执,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門译红,熙熙樓的掌柜王于貴愁眉苦臉地迎上來预茄,“玉大人,你說我怎么就攤上這事〕苌拢” “怎么了拙徽?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)诗宣。 經(jīng)常有香客問我膘怕,道長(zhǎ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
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼抹凳!你這毒婦竟也來了遏餐?” 一聲冷哼從身側(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ú)居荒郊野嶺守林人離奇死亡粹庞,尸身上長(zhǎng)有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
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宫静,地道東北人走净。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像孤里,于是被迫代替她去往敵國(guó)和親伏伯。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

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