作為Android開發(fā)者都知道在子線程中使用Handler必須要創(chuàng)建Looper氮发,其實HandlerThread就是在線程中封裝了Looper的創(chuàng)建和循環(huán)湿弦,不用我們開發(fā)者自己去創(chuàng)建它环肘,下面我們來看看源碼
源碼
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
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() {
}
@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)建的時候設置優(yōu)先級,我們來看看它的run方法狮斗,挑重點看
//創(chuàng)建looper绽乔,保存到ThreadLocal線程中
Looper.prepare();
synchronized (this) {
//得到創(chuàng)建的Looper
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//啟動循環(huán)Looper中的消息隊列
Looper.loop();
很簡單,就是創(chuàng)建了Looper并且啟動循環(huá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;
}
得到剛才創(chuàng)建的Looper對象折砸。
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
釋放Looper消息隊列里的消息。
到此HandlerThread的源碼就解析完了沙峻。