1.为什么使用?
_定义单一子线程,该子线程的的生命周期更方便控制,除非主观意图回收(调用looper.quit()),线程能够一直存活并且能够和线程通信,可安排任务代码在该子线程执行_
2.常见的用法:
HandlerThread handlerThread = new HandlerThread("name");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
本身HandlerThread的使用是微乎其微的点,N久以来我并没有使用过HandlerThread,直到最近两个月看到两个项目中用了HandlerThread,项目里也是常见的用法,在一些场景下我觉得使用的并不合理,在此做个记录。其中一个项目使用时还出了一些线程安全问题,排查问题时看了一下源码,其实源码非常简单.
个人感觉直接在当前线程handlerThread.getLooper()这种使用方式并不友好,
```java
public Looper getLooper() {
//线程调用了start()的话isAlive()即为true
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;
}
```
这里我们可以看到HandlerThread设计时考虑到了多线程的场景,采用了非公平锁synchronized+状态循环判断来处理,如果handlerThread线程并没有真用运行起来的话(没有调用run方法),会将调用getLooper()的线程挂起,直到handlerThread线程被真正启动了,想想如果当前线程为主线程的话,主线程就被wait()了!!!
可以根据实际业务场景,重写onLooperPrepared(),onLooperPrepared()是在handlerThread子线程调用的,而且此方法调用时,handlerThread子线程对应的handler和looper都已创建完成;
```java
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
```