handler和Thread的關(guān)聯(lián)

Looper

Looper是Handler和Thread相關(guān)聯(lián)的橋梁,也是APP開發(fā)中線程間通信的用的最多的一個(gè).
然而使用率卻是異常的低下,因?yàn)樵谙蛑骶€程交互的時(shí)Looper該做的工作已經(jīng)做好,使用上只需要在主線程創(chuàng)建Handler對(duì)象,然后再需要的地方發(fā)送消息即可.

參考博客 Android 異步消息處理機(jī)制 讓你深入理解 Looper监署、Handler蝇狼、Message三者關(guān)系 洪洋

Looper的初始化創(chuàng)建

Looper和線程的關(guān)系是一一對(duì)應(yīng)的,每一個(gè)線程有且只有一個(gè)Looper,可以從Looper的使用中看出.

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

在使用子線程中使用Hander時(shí),需要有Looper對(duì)象,而Looper的構(gòu)造函數(shù)是private修飾的,想要獲得創(chuàng)建一個(gè)Looper對(duì)象就只能調(diào)用靜態(tài)方法prepare.
在方法中我們可以看到調(diào)用了sThreadLocal.get()方法,返回的若非空就會(huì)拋出異常.這里就限定了一個(gè)線程只能有一個(gè)Looper.

Looper的構(gòu)造函數(shù)

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

在構(gòu)造函數(shù)中創(chuàng)建了一個(gè)MessageQueue(消息隊(duì)列).

Looper的使用

    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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

當(dāng)操作完成就可以調(diào)用Looper.loop();從代碼中可以看出在通過(guò)myLooper中拿到了當(dāng)前線程的Looper對(duì)象,獲取了對(duì)應(yīng)的MessageQueue之后,該線程會(huì)執(zhí)行一個(gè)死循環(huán),在死循環(huán)中不停的讀取MessageQueue隊(duì)列中的Message并調(diào)用 msg.target.dispatchMessage(msg);去處理該消息.

Handler

在使用Handler時(shí),我們通常都是實(shí)例化一個(gè)對(duì)象去發(fā)送消息,然后在handleMessage方法中去處理對(duì)應(yīng)的消息,并作出對(duì)應(yīng)的處理.

Hanlder的初始化

    public Handler() {
        this(null, false);
    }

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

在初始化中我們看到了Handler將自己和Looper進(jìn)行了關(guān)聯(lián),如若在子線程中未創(chuàng)建Looper就創(chuàng)建Hanlder那么便會(huì)拋出異常.并且在下面繼續(xù)獲取了Looper的消息隊(duì)列.

Handler的使用

        Message message = Message.obtain();
        message.what = TEXT;
        message.obj = (int) (Math.random() * 1000);
        mHandler.sendMessage(message);

Handler使用方式十分之簡(jiǎn)單,在需要使用的地方發(fā)送一個(gè)Message消息即可,在創(chuàng)建Handler時(shí)重寫handleMessage方法中處理對(duì)應(yīng)的Message消息即可.
多數(shù)人走到這一步就停下了,因?yàn)橐呀?jīng)知道如何使用Hanlder和Looper了,能滿足跨線程交互需求了,也就沒(méi)有繼續(xù)探索的愿望了,然后在面試的一個(gè)一問(wèn)Handler為什么能切換到主線程去執(zhí)行對(duì)應(yīng)的方法就懵逼了(面試問(wèn)懵逼好幾個(gè)了....)

Handler跨線程的原因

既然發(fā)送消息是在子線程,在handleMessage中處理的時(shí)候已經(jīng)到了主線程,那么線程切換的奧秘一定就在這兩個(gè)方法調(diào)用過(guò)程中,我們就從sendMessage方法中一步一步往下看.

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

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

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

到這里就可以看出一點(diǎn)端倪了,mQueue出現(xiàn)了,也就是Handler在創(chuàng)建時(shí)獲取的Looper的MessageQueue對(duì)象.
我們繼續(xù)向下看

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

在這里我們又看到了一點(diǎn)意思的東西,msg.target = this在Looper.loop中我們看到msg.target.dispatchMessage(msg);這么一行代碼,現(xiàn)在稍微一推敲就知道最終發(fā)生了什么,怎么切換線程的,但是我們還是繼續(xù)往下看.

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

恩,到這里就是將Message加入到消息隊(duì)列中去中去,hanlder中消息發(fā)送流程已經(jīng)走完了.
在這里handler將Message加入到了消息隊(duì)列中,而Looper一直線主線程中阻塞著,所以一收到消息就拿到了Message對(duì)象,然后在主線程中調(diào)用了Hanlder的處理方法.

Looper對(duì)消息的處理

從上面的分析已經(jīng)了解到了子線程和主線程是如何切換的,我們繼續(xù)看在主線程中Looper是如何處理發(fā)送過(guò)來(lái)的消息的.

    // Looper.loop();中代碼
    Message msg = queue.next(); // might block
    
    // MessageQueue中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;
        }
    }

瞧,我們發(fā)現(xiàn)了什么,又是一個(gè)死循環(huán)阻塞,原來(lái)主線程不是阻塞在Looper中,而是阻塞在MessageQueue對(duì)象中.
可以看到當(dāng)消息隊(duì)列有消息的時(shí)候立馬返回消息,沒(méi)有消息就阻塞(我就偷了個(gè)懶,不在繼續(xù)深入MessageQueue的原理了...)
Looper收到返回的消息會(huì)調(diào)用msg.target.dispatchMessage(msg)去處理,也就是調(diào)用Handler去處理.
我們繼續(xù)來(lái)到Hanlder的處理方法中.

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

msg.callback我們先放一放,就我們普通發(fā)送的Message通常是沒(méi)有callback對(duì)象的,下面的mCallback我們來(lái)看一看,該對(duì)象出現(xiàn)在構(gòu)造函數(shù)之中,通過(guò)構(gòu)造函數(shù)來(lái)賦值,我們來(lái)看看這個(gè)對(duì)象的定義

    public interface Callback {
        public boolean handleMessage(Message msg);
    }

可以看出就是一個(gè)接口,和自己重寫handleMessage一樣,只不過(guò)提供另一種方式來(lái)處理.(說(shuō)實(shí)話,在成員對(duì)象創(chuàng)建上面還重寫其方法,我感覺(jué)是看著挺難受的,這樣抽取成對(duì)象,然后通過(guò)構(gòu)造函數(shù)傳遞進(jìn)去,看著舒服多了.)
回到正題中來(lái),我們還剩下一個(gè)Messaged的callBack對(duì)象沒(méi)整明白.
首先,我們來(lái)看一看這究竟是一個(gè)什么對(duì)象.

    /*package*/ Runnable callback;

可以看到就是一個(gè)任務(wù)而已,而handleCallback(msg)方法點(diǎn)進(jìn)去再來(lái)看一看

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

只是單純的是運(yùn)行這個(gè)任務(wù)而已,但是這個(gè)任務(wù)是哪里來(lái)的呢?
答案在Handler,Handler不僅可以發(fā)消息給自己在主線程處理,也可以直接發(fā)送一個(gè)任務(wù)去主線程運(yùn)行.

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

到這里也就看明白了,剩下就和普通消息一樣的處理方式了.

文章到此結(jié)束,順便給自己打個(gè)小廣告,深圳求職,目前在職招人頂缸中(ps:找個(gè)人頂缸真不好招...全是假簡(jiǎn)歷)
簡(jiǎn)歷戳我

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異抗愁,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)搞隐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門驹愚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人劣纲,你說(shuō)我怎么就攤上這事逢捺。” “怎么了癞季?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵劫瞳,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我绷柒,道長(zhǎng)志于,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任废睦,我火速辦了婚禮伺绽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嗜湃。我一直安慰自己奈应,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布购披。 她就那樣靜靜地躺著杖挣,像睡著了一般。 火紅的嫁衣襯著肌膚如雪刚陡。 梳的紋絲不亂的頭發(fā)上惩妇,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天株汉,我揣著相機(jī)與錄音,去河邊找鬼歌殃。 笑死乔妈,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的氓皱。 我是一名探鬼主播褒翰,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼匀泊!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起朵你,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤各聘,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后抡医,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體躲因,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年忌傻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了大脉。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡水孩,死狀恐怖镰矿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情俘种,我是刑警寧澤秤标,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站宙刘,受9級(jí)特大地震影響苍姜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜悬包,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一衙猪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧布近,春花似錦垫释、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至季蚂,卻和暖如春茫船,著一層夾襖步出監(jiān)牢的瞬間琅束,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工算谈, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留涩禀,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓然眼,卻偏偏與公主長(zhǎng)得像艾船,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子高每,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

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