作为Android开发者都知道在子线程中使用Handler必须要创建Looper,其实HandlerThread就是在线程中封装了Looper的创建和循环,不用我们开发者自己去创建它,下面我们来看看源码
源码
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;
}
可以看出它就是一个普通的线程,创建的时候设置优先级,我们来看看它的run方法,挑重点看
//创建looper,保存到ThreadLocal线程中
Looper.prepare();
synchronized (this) {
//得到创建的Looper
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//启动循环Looper中的消息队列
Looper.loop();
很简单,就是创建了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;
}
得到刚才创建的Looper对象。
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
释放Looper消息队列里的消息。
到此HandlerThread的源码就解析完了。
网友评论