HandlerThread

說起HandlerThread我的確沒怎么用到過,以至于面試的時候被面試官問起時也是完全不知道。所以,今天就來補一補這個東西。其實這個類也不大,就149行代碼。下面就這英文看下意思,當然如果覺得英文煩躁,可以去掉英文就著我蹩腳的翻譯暫且看看:


/** 開啟一個帶有l(wèi)ooper的線程,start()方法必須調用(開啟線程肯定得調用start()方法啊!)。
 * 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;//優(yōu)先級
    int mTid = -1;//獲取調用進程的線程ID
    Looper mLooper;//Looper對象

    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.
     */
     //構造函數(shù):傳入一個String 對象做線程的名字,一個int值代表線程優(yōu)先級。
    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.
     */
     //可以重寫這個函數(shù)做一些準備工作,這個放方法在loop()方法調用之前調用。
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            //喚醒在等待的
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        //在loop()方法調用之前調用
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason is 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 {
                    //如果Looper未創(chuàng)建好,就先等待,對應上面的notifyAll();
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * 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
     */
     //直接退出,調用了looper.quit()方法;
    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.
     */
     //安全退出,調用了quitSafely()方法
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

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

大體意思:

在一個線程中創(chuàng)建了一個Looper對象,而我們知道Looper對象是消息機制的核心。那我們在子線程中弄這樣一個Looper對象就意味著該子線程也能像UI線程那樣,通過Handle進行線程之間的切換工作,從某個線程切換到該子線程中來。

那么,它到底有什么好處呢?

場景

我們來想一個場景,如果我們現(xiàn)在需要請求網(wǎng)絡數(shù)據(jù)(假設需要請求一張圖片,圖片請求返回后需要更新UI),我們都知道UI線程中不允許進行耗時的網(wǎng)絡請求。那么,我們通常會開啟一個子線程來進行請求:如果你不用網(wǎng)絡請求的三方庫,一般會通過new Thread。然后start()來完成吧!這樣的話,如果有多次請求圖片,那么我們就得new 很多個Thread。所以這是個問題?。?!

現(xiàn)在你就會想,難道(柯南BGM)你是說。。。沒錯,HandlerThread可以用來解決這個問題。還有這種騷操作?

問題解決分析

通過上面代碼我們知道:HandlerThread一個子線程,并且含有一個Looper。
再來看看那個問題:我們之所以需要new Thread。。然后start().是因為UI線程無法進行網(wǎng)絡請求,但是,HandlerThread可是一個子線程。。。重要的說三遍。所以,在它里面可以直接請求網(wǎng)絡,于是上面的new Thread 。。 start()問題就解決了。(臥槽。。。這也是騷操作?)。
當然,就憑他是個子線程還沒法說服我,雖然它是一個子線程不需要new Thread(),但是它自己也可能需要多次創(chuàng)建?。≈徊贿^是從new一個Thread變成了new HanderThread而已。這還不是沒卵用。(這這這。。。)

那么如何解釋它不需要重復創(chuàng)建呢?
其實也不難,只需要子線程不結束不就行了。(run方法中加個while(true)啊,呵呵),不過,它這里并不是while(true),而是用到了調用了一個loop()方法。

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

loop方法是阻塞的,所以它后面的語句在它未退出的(可以通過quit()方法和quitSafely()方法退出)時候是沒辦法執(zhí)行的。再加上它可以通過在外部實現(xiàn)一個Handler,然后,通過這個Handler給Looper發(fā)送message,近而源源不斷的實現(xiàn)網(wǎng)絡請求。所以,這就真正的解決了上面提出的那個問題。(我墻都不服。。。)

這里給一個連接,里面介紹了如何在外部創(chuàng)建一個Handler,然后源源不斷進行網(wǎng)絡請求。
鏈接地址:Android 多線程之HandlerThread 完全詳解

總結一下優(yōu)缺點:

引用一篇文章:

作者:Cooke_
鏈接:http://m.itdecent.cn/p/e9b2c0831b0d
來源:簡書

  1. HandlerThread將loop轉到子線程中處理,說白了就是將分擔MainLooper的工作量,降低了主線程的壓力,使主界面更流暢。
  2. 開啟一個線程起到多個線程的作用。處理任務是串行執(zhí)行,按消息發(fā)送順序進行處理。
  3. 相比多次使用new Thread(){…}.start()這樣的方式節(jié)省系統(tǒng)資源。
  4. 但是由于每一個任務都將以隊列的方式逐個被執(zhí)行到,一旦隊列中有某個任務執(zhí)行時間過長,那么就會導致后續(xù)的任務都會被延遲處理。
  5. HandlerThread擁有自己的消息隊列,它不會干擾或阻塞UI線程。
  6. 通過設置優(yōu)先級就可以同步工作順序的執(zhí)行,而又不影響UI的初始化;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容