HandlerThread面試知識小結

今天我們來回顧複習下HandlerThread, 當我們需要執行耗時任務時,需要開啓1個子線程來處理。如果在短時間內需要執行多個耗時任務時,就需要開始多個子線程來處理。多次創建和銷燬線程很損耗系統資源,怎麼解決這個問題呢?這就該今天的主角HandlerThread登場啦。

一、 HandlerThread 是什麼?

1、HandlerThread 本質上是一個線程類,繼承自Thread;

2、HandlerThread 有自己的內部Looper對象,可以進行Looper循環,創建Handler;

3、通過獲取HandlerThread的Looper對象傳遞給Handler對象,可以在Handler中的handlerMessage方法中執行耗時任務;

4、優點是異步不會阻塞UI線程,減少了對性能的損耗,缺點是不能同時進行多任務處理,需要按順利依次處理,處理效率較低;

5、與線程池注重併發不同,HandlerThread是一個串行隊列,它的背後只有的1個線程;

二、HandlerThread 源碼解析

1、在 run方法中 創建了Looper對象,調用了Looper.loop()方法開始消息輪詢。

2、在run()、getLooper()使用synchronized 同步鎖來保證線程同步安全。

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    private @Nullable Handler mHandler;

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

    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.  
     * @return The 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;
    }

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

    /**
     * Quits the handler thread's looper.
     * <p>
     * Causes the handler thread's looper to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     *
     * @see #quitSafely
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    /**
     * Quits the handler thread's looper safely.
     * <p>
     * Causes the handler thread's looper to terminate as soon as all remaining messages
     * in the message queue that are already due to be delivered have been handled.
     * Pending delayed messages with due times in the future will not be delivered.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p>
     * If the thread has not been started or has finished (that is if
     * {@link #getLooper} returns null), then false is returned.
     * Otherwise the looper is asked to quit and true is returned.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     */
    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;
    }
}


三、代碼實踐


package com.example.ling.review.handlerthread;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.ling.review.R;

public class HandlerThreadActivity extends AppCompatActivity {

    private HandlerThread mHandlerThread = null;
    private Handler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread);

        // 創建一個handlerThread 線程,線程名字:mHandler-thread
        mHandlerThread = new HandlerThread("handler-thread");
        //開啓一個線程
        mHandlerThread.start();

        // 在handlerThread線程中創建Handler
        //這個方法是運行在 handler-thread 線程中的 ,可以執行耗時操作
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                //這個方法是運行在 handler-thread 線程中的 ,可以執行耗時操作
                Log.d("mHandler ", "消息: " + msg.what + "  線程: " + Thread.currentThread().getName());
            }
        };

        // 在主線程handler發送消息
        mHandler.sendEmptyMessage(1);

        //在子線程給handler發送消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(2);
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 釋放資源
        mHandlerThread.quit();
    }
}


輸出日誌如下:

01-28 16:21:27.420 2580-3226/com.example.ling.review D/handler: 消息: 1 線程: handler-thread
01-28 16:21:27.421 2580-3226/com.example.ling.review D/handler: 消息: 2 線程: handler-thread

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章