作為Android開發(fā)者都知道在子線程中使用Handler必須要?jiǎng)?chuàng)建Looper,其實(shí)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;
}
可以看出它就是一個(gè)普通的線程,創(chuàng)建的時(shí)候設(shè)置優(yōu)先級(jí),我們來看看它的run方法,挑重點(diǎn)看
//創(chuàng)建looper,保存到ThreadLocal線程中
Looper.prepare();
synchronized (this) {
//得到創(chuàng)建的Looper
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//啟動(dòng)循環(huán)Looper中的消息隊(duì)列
Looper.loop();
很簡單,就是創(chuàng)建了Looper并且啟動(dòng)循環(huán)消息隊(duì)列。
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對(duì)象。
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
釋放Looper消息隊(duì)列里的消息。
到此HandlerThread的源碼就解析完了。