Android多線程之HandlerThread源碼解析

1、概述android

先來了解一下HandlerThread的幾個特性app

  • HandlerThread繼續於Thread,自己就是一個線程類
  • HandlerThread在內部維護了本身的Looper對象,因此能夠進行Looper循環
  • 建立HandlerThread後須要先調用HandlerThread.start()方法再向其下發任務,經過run()方法來建立Looper對象
  • 經過傳遞HandlerThread的Looper對象給Handler對象,從而能夠經過Handler來向HandlerThread下發號是任務

2、使用方式ide

再來看HandlerThread的使用方式函數

建立HandlerThread並調用start()方法,使其在子線程內建立Looper對象oop

HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();

而後以HandlerThread內部的Looper對象爲參數建立一個Handler,經過Handler向子線程發送Message,以此下發耗時任務,消息的接受者與任務的處理者則由回調函數ChildCallback來完成源碼分析

Handler childThreadHandler = new Handler(handlerThread.getLooper(), new ChildCallback());
    
    //Callback 運行於子線程
    private class ChildCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            //在此能夠進行耗時操做
            //若是須要更新UI,則須要經過主線程的Handler來完成
            return false;
        }
    }

完整的實列代碼以下所示ui

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    //Callback 運行於子線程
    private class ChildCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            //在此能夠進行耗時操做
            //若是須要更新UI,則須要經過主線程的Handler來完成
            Log.e(TAG, "ChildCallback 當前線程名:" + Thread.currentThread().getName() + "   " + "當前線程ID:" + Thread.currentThread().getId());
            Log.e(TAG, "耗時任務開始");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "耗時任務結束");
            //通知界面更新UI
            uiHandler.sendEmptyMessage(1);
            return false;
        }
    }

    //運行於主線程的Handler,用於更新UI
    @SuppressLint("HandlerLeak")
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.e(TAG, "uiHandler 當前線程名:" + Thread.currentThread().getName() + "   " + "當前線程ID:" + Thread.currentThread().getId());
            Toast.makeText(MainActivity.this, "耗時操做完成", Toast.LENGTH_LONG).show();
        }
    };

    //用於向子線程發佈耗時任務的Handler
    private Handler childThreadHandler;

    private HandlerThread handlerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        childThreadHandler = new Handler(handlerThread.getLooper(), new ChildCallback());
        Log.e(TAG, "onCreate 當前線程名:" + Thread.currentThread().getName() + "   " + "當前線程ID:" + Thread.currentThread().getId());
    }

    public void startTask(View view) {
        childThreadHandler.sendEmptyMessage(1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();
        childThreadHandler.removeCallbacksAndMessages(null);
    }

}

程序運行後的日誌以下所示,能夠看出各個方法在調用時所處的線程this

06-22 02:51:41.779 21977-21977/com.summer.myapplication E/MainActivity: onCreate 當前線程名:main   當前線程ID:2
06-22 02:51:44.927 21977-21995/com.summer.myapplication E/MainActivity: ChildCallback 當前線程名:HandlerThread   當前線程ID:497
06-22 02:51:44.928 21977-21995/com.summer.myapplication E/MainActivity: 耗時任務開始
06-22 02:51:49.930 21977-21995/com.summer.myapplication E/MainActivity: 耗時任務結束
06-22 02:51:49.930 21977-21977/com.summer.myapplication E/MainActivity: uiHandler 當前線程名:main   當前線程ID:2

3、源碼分析線程

先看下HandlerThread的類聲明日誌

Thread的子類

public class HandlerThread extends Thread

兩個構造函數,能夠傳入的參數分別是線程名和線程優先級

public HandlerThread(String name) {
        super(name);
        //使用默認的線程優先級
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        //使用自定義的線程優先級
        mPriority = priority;
    }

看下run() 方法

@Override
    public void run() {
        mTid = Process.myTid();
        //觸發當前線程建立 Looper 對象
        Looper.prepare();
        synchronized (this) {
            //獲取 Looper 對象
            mLooper = Looper.myLooper();
            //喚醒在等待的線程
            //喚醒 getLooer() 中可能還處於等待狀態的線程
            notifyAll();
        }
        //設置線程優先級
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        //開啓消息循環
        Looper.loop();
        mTid = -1;
    }

Looper.prepare()方法用於爲當前線程建立一個Looper對象,在主線程須要依賴此Looper對象來構建一個Handler對象,經過Handler對象來向子線程下發耗時任務

以後能夠看到有一個同步代碼塊,在當中調用了notifyAll()來喚醒等待線程,那該喚醒的又是那個線程呢?這裏須要明確各個方法是運行於那個線程,run()方法確定是運行在子線程中, 但用於想HandlerThread下發任務的Handler是初始化於主線程,所以getlooper()方法也是運行於主線程的。因爲是兩個不一樣的線程,run()方法和getLooper()的運行前後順序是不明確的,所以getLooper()方法須要確保Looper對象不爲null 時才返回,不然將一直阻塞等待Looper對象初始化完成

//獲取與當前線程關聯的 Looper 對象
   //由於 getLooper() 方法可能先於 run() 被調用,此時就須要先等待 Looper 對象被建立
   public Looper getLooper() {
       //若是當前線程未在運行,則返回 null 
       if (!isAlive()) {
           return null;
       }
       synchronized (this) {
           //若是當前線程已處理運行狀態(已調用 start() 方法)且 Looper 對象還未建立
           //則調用 wait() 方法釋放鎖,等待 Looper 對象建立
           while (isAlive() && mLooper == null) {
               try {
                   wait();
               } catch (InterruptedException e) {
               }
           }
       }
       return mLooper;
   }

Looper對象初始化完成後,就須要調用Looper.loop()來開啓消息循環,至此HandlerThread的初始化操做就完成了

HandlerThread的完整源碼註釋

package android.os;

import android.annotation.NonNull;
import android.annotation.Nullable;

/**
 * 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.
 */
public class HandlerThread extends Thread {

    //線程優先級
    int mPriority;

    //線程ID
    int mTid = -1;

    //當前線程持有的Looper對象
    Looper mLooper;

    //包含當前 Looper 對象的 Handler
    private @Nullable Handler mHandler;

    public HandlerThread(String name) {
        super(name);
        //使用默認的線程優先級
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        //使用自定義的線程優先級
        mPriority = priority;
    }
    
    //在 Looper 循環啓動前調用
    //此處是空實現,留待子類重寫
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        //觸發當前線程建立 Looper 對象
        Looper.prepare();
        synchronized (this) {
            //獲取 Looper 對象
            mLooper = Looper.myLooper();
            //喚醒在等待的線程
            //喚醒 getLooer() 中可能還處於等待狀態的線程
            notifyAll();
        }
        //設置線程優先級
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        //開啓消息循環
        Looper.loop();
        mTid = -1;
    }
    
    //獲取與當前線程關聯的 Looper 對象
    //由於 getLooper() 方法可能先於 run() 被調用,此時就須要先等待 Looper 對象被建立
    public Looper getLooper() {
        //若是當前線程未在運行,則返回 null 
        if (!isAlive()) {
            return null;
        }
        synchronized (this) {
            //若是當前線程已處理運行狀態(已調用 start() 方法)且 Looper 對象還未建立
            //則調用 wait() 方法釋放鎖,等待 Looper 對象建立
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

    //清空消息隊列中全部的消息
    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;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }

}
相關文章
相關標籤/搜索