Android HandlerThread源碼解析

作為Android開發(fā)者都知道在子線程中使用Handler必須要?jiǎng)?chuàng)建Looper,其實(shí)HandlerThread就是在線程中封裝了Looper的創(chuàng)建和循環(huán),不用我們開發(fā)者自己去創(chuàng)建它,下面我們來看看源碼

源碼
public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    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() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

可以看出它就是一個(gè)普通的線程,創(chuàng)建的時(shí)候設(shè)置優(yōu)先級(jí),我們來看看它的run方法,挑重點(diǎn)看

 //創(chuàng)建looper,保存到ThreadLocal線程中
 Looper.prepare();
 synchronized (this) {
      //得到創(chuàng)建的Looper
      mLooper = Looper.myLooper();
      notifyAll();
  }
  Process.setThreadPriority(mPriority);
  onLooperPrepared();
  //啟動(dòng)循環(huán)Looper中的消息隊(duì)列
  Looper.loop();

很簡單,就是創(chuàng)建了Looper并且啟動(dòng)循環(huán)消息隊(duì)列。

public Looper getLooper() {
     if (!isAlive()) {
          return null;
     }
        
    // If the thread has been started, wait until the looper has been created.
    synchronized (this) {
         while (isAlive() && mLooper == null) {
            try {
                wait();
             } catch (InterruptedException e) {
            }
          }
     }
        return mLooper;
 }

得到剛才創(chuàng)建的Looper對(duì)象。

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

釋放Looper消息隊(duì)列里的消息。

到此HandlerThread的源碼就解析完了。

最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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