一、HandlerThread的使用
//创建实例对象
HandlerThread handlerThread=new HandlerThread("thread_handler");
//开启循环
handlerThread.start();
//创建handler,looper使用的是handlerThread的looper
Handler handler=new Handler(handlerThread.getLooper()){
@Override
public void handleMessage(Message msg) {
//工作线程中处理问题
super.handleMessage(msg);
}
};
//发送消息
handler.sendEmptyMessage(0);
//结束线程,停止消息循环
handlerThread.quit();
二、HandlerThread的源码分析
1、HandlerThread是Thread的子类,线程类
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
2、当我们调用start方法后,HandlerThread会执行run方法,run方法创建当前线程的Looper,并把创建的looper赋值给成员变量mLooper.
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
3、初始化Handler的时候,把工作线程的looper作为参数传入,所以handler就能操作工作线程looper和messageQueue,创建完handler实例,就可以发送消息了。
Handler handler=new Handler(handlerThread.getLooper()){
@Override
public void handleMessage(Message msg) {
//工作线程中处理问题
super.handleMessage(msg);
}
};
这里HandlerThread的getLooper方法,当判断当前线程的Looper还没创建后(就是还没有调用线程的start()),他会阻塞当前线程。
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;
}
4、当不想使用工作线程了,需要停止消息循环,这一步必须,否则工作线程的looper一直运行。
handlerThread.quit();
handlerThread.quitSafely();
三、Handler,Thread,HandlerThread的区别
- Handler在Andorid中负责发送和处理消息,通过它可以实现工作线程和主线程的消息通讯。
- Thread 线程,是CPU调度和分配的基本单位
- HandlerThread 一个继承自Thread类的HandlerThread,run方法中创建了工作线程的Looper,可以用于工作线程的消息循环