一、HandlerThread是什麼
用於防止Looper拿到空指針,下面讓我們來看看,它是如何操作的吧
1.Looper 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;
}
2.handlerThread.run()方法
public void run() {
mTid = Process.myTid();
Looper.prepare();//創建一個Looper對象
synchronized (this) {
mLooper = Looper.myLooper();//把Looper對象複製給MyLooper
notifyAll();//通知notify方法,MyLooper就能喚醒在等待當前線程的對象,Handler就能拿到對象,則不會報出空指針問題
}//線程同步之間的判斷
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
二、總結
總結: 因此在開發中,可以用handlerThread去模擬一個異步任務的一種操作,只需在主線程中給子線程發送消息,讓子線程去處理一些耗時的操作(例如:下載網絡圖片、更新數據庫)只要在handlerThread‘中去創建一個Looper,再與一個默認的Handler進行關聯,所有的handleMessage方法都是在子線程中去調用。在設計時,可以減輕考慮開啓幾個線程,開啓線程之後,再異步任務中添加要執行的任務(要考慮存儲結構),什麼時候添加、移除、傳遞開發的負擔。