HandlerThread
顧名思義晒屎,HandlerThread它是一個(gè)Thread淫半,是Google為提高開發(fā)者效率封裝的一個(gè)類逆济。
與普通的Thread不同的是榛斯,它有一個(gè)成員屬性 Looper,而Looper是用來干嘛的前一章節(jié)我們已經(jīng)介紹過了永票。也就是說卵贱,我們的HandlerThread具有了Looper的功能。如果你有看過HandlerThread的源碼侣集,你會(huì)發(fā)現(xià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;
}
沒錯(cuò)编振,這就是我們?cè)谧泳€程里使用Handler時(shí)的典型用法
Looper.prepare(), Looper.loop()的使用臭埋,不同的是這里使用了一個(gè)鎖踪央,
synchronized我們當(dāng)前的這個(gè)類實(shí)例,并且調(diào)用notifyAll()瓢阴。為什么要多寫這個(gè)呢畅蹂?看到這里我也不曉得。
當(dāng)我們對(duì)消息隊(duì)列的處理影響到性能的時(shí)候荣恐,比如頁面上的卡頓或者比較耗時(shí)的任務(wù)液斜,那我們就可以考慮使用HandlerThread了,來看看他的用法:
private Handler mHandler;
private HandlerThread mHandlerThread;
public void initHandler() {
mHandlerThread = new HandlerThread(Tag);
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
}
我們知道叠穆,在主線程里使用Hander少漆,我們不需要再調(diào)用Looper.prepare()和Looper.loop(),因?yàn)橄到y(tǒng)已經(jīng)幫我們處理好了痹束,主線程里的Handler使用的主線程的Looper检疫。
使用HandlerThread,我們就可以在初始化Handler的時(shí)候讶请,將HandlerThread里的Looper傳遞給Handler祷嘶。這樣屎媳,主線程里Handler消息處理就會(huì)被轉(zhuǎn)移到子線程里,這樣一定程度上減少了主線程的壓力论巍。
回頭來看源碼烛谊,
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;
}
初始化時(shí)getLooper(),我們發(fā)現(xiàn),這里也有一個(gè)鎖嘉汰,也是鎖住HandlerThread類實(shí)例丹禀。start HandlerThread時(shí),會(huì)調(diào)用其run方法鞋怀,run方法里會(huì)調(diào)用 Looper.prepare() 需要一定的時(shí)間, 所以在new Handler時(shí)双泪,wait()方法等待Looper初始化完成,所以在run方法里才會(huì)有
notifyAll()的調(diào)用密似。
以上就是對(duì)HandlerThread的分析焙矛,是不是挺簡單的呢?
根據(jù)以上的分析我們可以總結(jié)出:
- HandlerThread將Looper轉(zhuǎn)移到子線程中處理残腌,降低主線程的壓力村斟,不會(huì)阻塞主線程,界面顯示會(huì)更流暢
- 子線程處理消息抛猫,因此可以處理一些比較耗時(shí)的單個(gè)任務(wù)蟆盹。
- 由于使用消息隊(duì)列的處理方式,故并發(fā)的多任務(wù)并不適用HandlerThread闺金,會(huì)造成嚴(yán)重的阻塞