Android HandlerThread 源碼分析

HandlerThread 簡介:

咱們知道Thread線程是一次性消費品,當Thread線程執行完一個耗時的任務以後,線程就會被自動銷燬了。若是此時我又有一html

個耗時任務須要執行,咱們不得不從新建立線程去執行該耗時任務。然而,這樣就存在一個性能問題:屢次建立和銷燬線程是很耗java

系統資源的。爲了解這種問題,咱們能夠本身構建一個循環線程Looper Thread,當有耗時任務投放到該循環線程中時,線程執行耗android

時任務,執行完以後循環線程處於等待狀態,直到下一個新的耗時任務被投放進來。這樣一來就避免了屢次建立Thread線程致使的安全

性能問題了。也許你能夠本身去構建一個循環線程,但我能夠告訴你一個好消息,Aandroid SDK中其實已經有一個循環線程的框架微信

了。此時你只須要掌握其怎麼使用的就ok啦!固然就是咱們今天的主角HandlerThread啦!接下來請HandlerThread上場,鼓掌~~app

HandlerThread的父類是Thread,所以HandlerThread實際上是一個線程,只不過其內部幫你實現了一個Looper的循環而已。那麼咱們框架

先來了解一下Handler是怎麼使用的吧!異步

【轉載請註明出處:Android HandlerThread 源碼分析 廢墟的樹】ide

HandlerThread使用步驟:

1.建立實例對象

HandlerThread handlerThread = new HandlerThread("handlerThread");

以上參數能夠任意字符串,參數的做用主要是標記當前線程的名字。oop

2.啓動HandlerThread線程

handlerThread.start();

到此,咱們就構建完一個循環線程了。那麼你可能會懷疑,那我怎麼將一個耗時的異步任務投放到HandlerThread線程中去執行呢?固然是有辦法的,接下來看第三部。

3.構建循環消息處理機制

Handler subHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //實現本身的消息處理
                return true;
            }
        });

第三步建立一個Handler對象,將上面HandlerThread中的looper對象最爲Handler的參數,而後重寫Handler的Callback接口類中的

handlerMessage方法來處理耗時任務。

總結:以上三步順序不能亂,必須嚴格按照步驟來。到此,咱們就能夠調用subHandler以發送消息的形式發送耗時任務到線程

HandlerThread中去執行。言外之意就是subHandler中Callback接口類中的handlerMessage方法實際上是在工做線程中執行的。

HandlerThread實例:

package com.example.handlerthread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Handler mSubHandler;
    private TextView textView;
    private Button button;

    private Handler.Callback mSubCallback = new Handler.Callback() {
        //該接口的實現就是處理異步耗時任務的,所以該方法執行在子線程中
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
            case 0:
                Message msg1 = new Message();
                msg1.what = 0;
                msg1.obj = java.lang.System.currentTimeMillis();
                mUIHandler.sendMessage(msg1);
                break;

            default:
                break;
            }

            return false;
        }
    };

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

        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);

        HandlerThread workHandle = new HandlerThread("workHandleThread");
        workHandle.start();
        mSubHandler = new Handler(workHandle.getLooper(), mSubCallback);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //投放異步耗時任務到HandlerThread中
                mSubHandler.sendEmptyMessage(0);
            }
        });

    }
}

HandlerThread源碼分析

HandlerThread構造方法

/**
 * 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;
    
    //構造方法
    public HandlerThread(String name) {
        //調用父類默認的方法建立線程
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
   //帶優先級參數的構造方法
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

...............

}

分析:該類開頭就給出了一個描述:該類用於建立一個帶Looper循環的線程,Looper對象用於建立Handler對象,值得注意的是在建立Handler

對象以前須要調用start()方法啓動線程。這裏可能有些人會有疑問?爲啥須要先調用start()方法以後才能建立Handler呢?後面咱們會解答。

上面的代碼註釋已經很清楚了,HandlerThread類有兩個構造方法,不一樣之處就是設置當前線程的優先級參數。你能夠根據本身的狀況來設置優先

級,也能夠使用默認優先級。

HandlerThrad的run方法

public class HandlerThread extends Thread {
  /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        //得到當前線程的id
        mTid = Process.myTid();
        //準備循環條件
        Looper.prepare();
        //持有鎖機制來得到當前線程的Looper對象
        synchronized (this) {
            mLooper = Looper.myLooper();
            //發出通知,當前線程已經建立mLooper對象成功,這裏主要是通知getLooper方法中的wait
            notifyAll();
        }
        //設置當前線程的優先級
        Process.setThreadPriority(mPriority);
        //該方法實現體是空的,子類能夠實現該方法,做用就是在線程循環以前作一些準備工做,固然子類也能夠不實現。
        onLooperPrepared();
        //啓動loop
        Looper.loop();
        mTid = -1;
    }
}

分析:以上代碼中的註釋已經寫得很清楚了,以上run方法主要做用就是調用了Looper.prepare和Looper.loop構建了一個循環線程。值得一提的

是,run方法中在啓動loop循環以前調用了onLooperPrepared方法,該方法的實現是一個空的,用戶能夠在子類中實現該方法。該方法的做用是

在線程loop以前作一些初始化工做,固然你也能夠不實現該方法,具體看需求。由此也能夠看出,Google工程師在編寫代碼時也考慮到代碼的可擴展性。牛B!

HandlerThread的其餘方法

getLooper得到當前線程的Looper對象

/**
     * 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() {
        //若是線程不是存活的,則直接返回null
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        //若是線程已經啓動,可是Looper還未建立的話,就等待,知道Looper建立成功
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

分析:其實方法開頭的英文註釋已經解釋的很清楚了:該方法主要做用是得到當前HandlerThread線程中的mLooper對象。

首先判斷當前線程是否存活,若是不是存活的,這直接返回null。其次若是當前線程存活的,在判斷線程的成員變量mLooper是否爲null,若是爲

null,說明當前線程已經建立成功,可是還沒來得及建立Looper對象,所以,這裏會調用wait方法去等待,當run方法中的notifyAll方法調用以後

通知當前線程的wait方法等待結束,跳出循環,得到mLooper對象的值。

總結:在得到mLooper對象的時候存在一個同步的問題,只有當線程建立成功而且Looper對象也建立成功以後才能得到mLooper的值。這裏等待方法wait和run方法中的notifyAll方法共同完成同步問題。

quit結束當前線程的循環

/**
     * 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;
    }
//安全退出循環
 public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

分析:以上有兩種讓當前線程退出循環的方法,一種是安全的,一中是不安全的。至於二者有什麼區別? quitSafely方法效率比quit方法標率低一點,可是安全。具體選擇哪一種就要看具體項目了。

總結:

1.HandlerThread適用於構建循環線程。

2.在建立Handler做爲HandlerThread線程消息執行者的時候必須調用start方法以後,由於建立Handler須要的Looper參數是從HandlerThread類中得到,而Looper對象的賦值又是在HandlerThread的run方法中建立。

3.關於HandlerThread和Service的結合使用請參考另外一篇博客:Android IntentService 源碼分析

【轉載請註明出處:Android HandlerThread 源碼分析 廢墟的樹】

掃碼關注微信公衆號「Android知識傳播」,不定時傳播經常使用Android基礎知識。

Android知識傳播

相關文章
相關標籤/搜索