HandlerThread特點
- HandlerThread本質(zhì)上是一個線程類,它繼承了Thread端盆;
- HandlerThread有自己的內(nèi)部Looper對象,可以進行l(wèi)ooper循環(huán);
- 通過獲取HandlerThread的looper對象傳遞給Handler對象件甥,可以在handleMessage方法中執(zhí)行異步任務(wù)何恶。
- 創(chuàng)建HandlerThread后必須先調(diào)用HandlerThread.start()方法孽锥,Thread會先調(diào)用run方法,創(chuàng)建Looper對象细层。
HandlerThread使用步驟
1.創(chuàng)建實例對象
HandlerThread handlerThread = new HandlerThread("hanlder_thread");
傳入?yún)?shù)的作用主要是標記當前線程的名字惜辑,可以任意字符串。
2.啟動HandlerThread線程
//必須先開啟線程
handlerThread.start();
到此疫赎,我們創(chuàng)建完HandlerThread并啟動了線程盛撑。那么我們怎么將一個耗時的異步任務(wù)投放到HandlerThread線程中去執(zhí)行呢?接下來看下面步驟:
3.構(gòu)建循環(huán)消息處理機制
/**
* 該callback運行于子線程
*/
class ChildCallback implements Handler.Callback {
@Override
public boolean handleMessage(Message msg) {
//在子線程中進行相應的網(wǎng)絡(luò)請求
//通知主線程去更新UI
mUIHandler.sendMessage(msg1);
return false;
}
}
4.構(gòu)建異步handler
//子線程Handler
Handler childHandler = new Handler(handlerThread.getLooper(),new ChildCallback());
第3步和第4步是構(gòu)建一個可以用于異步操作的handler捧搞,并將前面創(chuàng)建的HandlerThread的Looper對象以及Callback接口類作為參數(shù)傳遞給當前的handler抵卫,這樣當前的異步handler就擁有了HandlerThread的Looper對象狮荔,由于HandlerThread本身是異步線程,因此Looper也與異步線程綁定介粘,從而handlerMessage方法也就可以異步處理耗時任務(wù)了轴合,這樣我們的Looper+Handler+MessageQueue+Thread異步循環(huán)機制構(gòu)建完成。
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;//線程優(yōu)先級
int mTid = -1;
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.
*/
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() {
}
從源碼可以看出HandlerThread繼續(xù)自Thread,構(gòu)造函數(shù)的傳遞參數(shù)有兩個碗短,一個是name指的是線程的名稱受葛,一個是priority指的是線程優(yōu)先級,我們根據(jù)需要調(diào)用即可偎谁。其中成員變量mLooper就是HandlerThread自己持有的Looper對象总滩。onLooperPrepared()該方法是一個空實現(xiàn),是留給我們必要時可以去重寫的巡雨,但是注意重寫時機是在Looper循環(huán)啟動前闰渔,再看看run方法:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll(); //喚醒等待線程
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
在創(chuàng)建HandlerThread對象后必須調(diào)用其start()方法才能進行其他操作,而調(diào)用start()方法后相當于啟動了線程铐望,也就是run方法將會被調(diào)用冈涧,而我們從run源碼中可以看出其執(zhí)行了 - Looper.prepare() - 代碼,這時Looper對象將被創(chuàng)建正蛙,當Looper對象被創(chuàng)建后將綁定在當前線程(也就是當前異步線程)督弓,這樣我們才可以把Looper對象賦值給Handler對象,進而確保Handler對象中的handleMessage方法是在異步線程執(zhí)行的乒验。接著將執(zhí)行代碼:
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll(); //喚醒等待線程
}
這里在Looper對象創(chuàng)建后將其賦值給HandlerThread的內(nèi)部變量mLooper愚隧,并通過notifyAll()方法去喚醒等待線程,最后執(zhí)行Looper.loop();代碼锻全,開啟looper循環(huán)語句狂塘。那這里為什么要喚醒等待線程呢?我們來看看鳄厌,getLooper方法
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;
}
事實上可以看出外部在通過getLooper方法獲取looper對象時會先先判斷當前線程是否啟動了荞胡,如果線程已經(jīng)啟動,那么將會進入同步語句并判斷Looper是否為null了嚎,為null則代表Looper對象還沒有被賦值泪漂,也就是還沒被創(chuàng)建,此時當前調(diào)用線程進入等待階段新思,直到Looper對象被創(chuàng)建并通過 notifyAll()方法喚醒等待線程窖梁,最后才返回Looper對象,之所以需要等待喚醒機制夹囚,是因為Looper的創(chuàng)建是在子線程中執(zhí)行的纵刘,而調(diào)用getLooper方法則是在主線程進行的,這樣我們就無法保障我們在調(diào)用getLooper方法時Looper已經(jīng)被創(chuàng)建荸哟,到這里我們也就明白了在獲取mLooper對象時會存在一個同步的問題假哎,只有當線程創(chuàng)建成功并且Looper對象也創(chuàng)建成功之后才能獲得mLooper的值瞬捕,HandlerThread內(nèi)部則通過等待喚醒機制解決了同步問題。
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;
}
從源碼可以看出當我們調(diào)用quit方法時舵抹,其內(nèi)部實際上是調(diào)用Looper的quit方法而最終執(zhí)行的則是MessageQueue中的removeAllMessagesLocked方法(Handler消息機制知識點)肪虎,該方法主要是把MessageQueue消息池中所有的消息全部清空,無論是延遲消息(延遲消息是指通過sendMessageDelayed或通過postDelayed等方法發(fā)送)還是非延遲消息惧蛹。
??當調(diào)用quitSafely方法時扇救,其內(nèi)部調(diào)用的是Looper的quitSafely方法而最終執(zhí)行的是MessageQueue中的removeAllFutureMessagesLocked方法,該方法只會清空MessageQueue消息池中所有的延遲消息香嗓,并將消息池中所有的非延遲消息派發(fā)出去讓Handler去處理完成后才停止Looper循環(huán)迅腔,quitSafely相比于quit方法安全的原因在于清空消息之前會派發(fā)所有的非延遲消息。最后需要注意的是Looper的quit方法是基于API 1靠娱,而Looper的quitSafely方法則是基于API 18的沧烈。