HandlerThread 源碼解析

HandlerThread 是什么?

系統(tǒng)對(duì) HandlerThread 的解釋是這么一段話:

Handy class for starting a new thread that has a looper. The looper can then be 
used to create handler classes. Note that start() must still be called.

從上面這段話可以看出,HandlerThread 是一個(gè)是可以創(chuàng)建帶有looper新線程的類,而這個(gè) looper 是用來創(chuàng)建 handler 類的。需要注意的是HandlerThread 在創(chuàng)建后必須 調(diào)用 他的 start() 方法。 這就是 HandlerThread 釋義了。至于怎么用 HandlerLooper這里就不做介紹了

源碼解析

  • HandlerThread的源碼不多只有150行,首先我們看他的構(gòu)造函數(shù)

    public class HandlerThread extends Thread {
    //線程優(yōu)先級(jí)
    int mPriority;
    //線程id
    int mTid = -1;
    //當(dāng)前線程持有的Looper對(duì)象
    Looper mLooper;
    
    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    
    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from 
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    
    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }
    

    可以看到有兩個(gè)構(gòu)造函數(shù)方法,一個(gè)參數(shù) name 值的是線程名稱,一個(gè)參數(shù) priority指的是線程優(yōu)先級(jí)。
    onLooperPrepared() 該方法是留給我們自己實(shí)現(xiàn)的。是在Looper創(chuàng)建完成后調(diào)用的。

  • 在前面介紹HandlerThread時(shí)介紹了必須要調(diào)用 start()方法 , 所以當(dāng)調(diào)用這個(gè)方法相當(dāng)于啟動(dòng)了線程,也就是run 方法將被調(diào)用。所以我們來看看 HandlerThread 重寫的 run方法

    @Override
    public void run() {
        //獲取線程id
        mTid = Process.myTid();
        //啟用Looper,當(dāng)Looper被創(chuàng)建后將綁定當(dāng)前線程
        Looper.prepare();
        synchronized (this) {
            //創(chuàng)建 Looper
            mLooper = Looper.myLooper();
            //喚醒等待線程
            notifyAll();
        }
        //設(shè)置線程優(yōu)先級(jí)
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        //讓Looper開始工作,從消息隊(duì)列里取消息,處理消息
        Looper.loop();
        mTid = -1;
    }

可以看到 在 run 方法里完成了將Looper綁定到當(dāng)前線程, Looper 的創(chuàng)建,喚醒等待的線程,設(shè)置線程優(yōu)先級(jí),調(diào)用onLooperPrepared() 方法,讓Looper 開始工作取消息處理消息。這里或許你有疑問,為什么要調(diào)用 notifyAll() 方法來喚醒等待的線程,看下面代碼就可以揭曉答案:

    public Looper getLooper() {
        //判斷當(dāng)前線程是否啟動(dòng),即是否調(diào)用了start()方法
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            //判斷Looper是否創(chuàng)建完成,如果沒有則一直調(diào)用 wait() 讓線程等待喚醒
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

  • 這里當(dāng)我們 調(diào)用 getLooper 時(shí),若 Looper還沒有創(chuàng)建完成,則會(huì)調(diào)用 wait() 讓線程一直處于等待喚醒狀態(tài),知道Looper創(chuàng)建完成并 通過notifyAll()方法喚醒等待的線程,最后返回 Looper對(duì)象。之所以有等待喚醒機(jī)制,是因?yàn)?code>Looper 在子線程里創(chuàng)建而 getLooper 是在主線程里調(diào)用,這里就會(huì)涉及到一個(gè)線程同步的問題,我們無法確保在調(diào)用 getLooper 時(shí)Looper 已經(jīng)被創(chuàng)建好。所以 HanlderLooper 這里采用了 等待喚醒來解決線程同步問題。



最后我們?cè)倏纯?剩下的兩個(gè)方法:

    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
    
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

  • 從源碼可以看出 當(dāng)我們調(diào)用 quit方法時(shí)實(shí)際調(diào)用了 looper.quit(),而最終執(zhí)行的是 MessageQueueremoveAllMessagesLocked 方法,該方法主要是把MessageQueue 的消息池中的所有消息全部清空,無論是延遲消息還是非延遲消息。
  • quitSafely() 則調(diào)用的是looper.quitSafely()( 需要注意的是looper.quitSafely() 方法是在 API 18 以后添加的)。而looper.quitSafely()最終調(diào)用的是 MessageQueueremoveAllFutureMessagesLocked 方法,該方法只會(huì)清空MessageQueue 消息池中所有的延遲消息,并將所有的非延遲消息派發(fā)出去讓 Handler 去處理完成后才停止 Looper 循環(huán)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容