1. HandlerThread是什么?
HandlerThread本質(zhì)上是一個線程類,它繼承了Thread;
HandlerThread有自己的內(nèi)部的Looper對象,可以進行l(wèi)ooper循環(huán);
通過獲取HandlerThread的looper對象傳遞給Handler對象,可以在handleMessage方法中執(zhí)行異步任務(wù);
2. HandlerThread產(chǎn)生背景:
當面試官在問我們Handler在子線程中怎么發(fā)送消息,這時候有人就會說了,我們可以拿到主線程的Looper或者通過手動調(diào)用Looper.prepare和Looper.loop,這顯然是可以的,這時候面試官可能來了一句:還有其他方式嘛?瞬間懵逼,有沒有?。。ㄈ绻麤]接觸過HandlerThread)其實,這種在子線程中發(fā)送消息的情況,google工程師早就給我們提供了,這就是HandlerThread的產(chǎn)生背景,它不需要我們?nèi)ツ弥骶€程的Looper,也不用手動調(diào)用Looper.prepare和Looper.loop,它已經(jīng)封裝了Looper,并手動調(diào)用了這兩個方法。
3. HandlerThread的特點:
- HandlerThread本質(zhì)上是一個線程類,它繼承了Thread;
- HandlerThread有自己的內(nèi)部的Looper對象,可以進行l(wèi)ooper循環(huán);
- 通過獲取HandlerThread的looper對象傳遞給Handler對象,可以在handleMessage法中執(zhí)行異步任務(wù);
- 優(yōu)點是不會有阻塞,減少了對性能的消耗,缺點是不能同時進行多任務(wù)的處理,需要等待進行處理,處理效率較低。
- 與線程池注重并發(fā)不同,HandlerThread是一個串行隊列,HandlerThread背后只有一個線程。
4. HandlerThread的機制原理:
HandlerThread是繼承Thread類的,本質(zhì)上是一個線程類,代碼比較簡單,主要看兩個方法run()和getLooper()。
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
在run方法中調(diào)用了Looper.prepare,創(chuàng)建了Looper對象,并將Looper對象綁定到當前線程中,同步機制獲取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;
}
喜歡本篇博客的簡友們,就請來一波點贊,您的每一次關(guān)注,將成為我前進的動力,謝謝!