Android HandlerThread源碼解析

作為Android開發者都知道在子線程中使用Handler必須要創建Looper,其實HandlerThread就是在線程中封裝了Looper的創建和循環,不用我們開發者自己去創建它,下面我們來看看源碼

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

可以看出它就是一個普通的線程,創建的時候設置優先級,我們來看看它的run方法,挑重點看

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

很簡單,就是創建了Looper并且啟動循環消息隊列。

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

得到剛才創建的Looper對象。

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

釋放Looper消息隊列里的消息。

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容