异步通信3——handlerThread详解

217 阅读1分钟

HandlerThread产生背景
开启Thread子线程进行耗时操作,多次创建和销毁线程是很耗系统资源的。

一、 HandlerThread是什么

handler+thread+looper
是一个thread内部有looper

HandlerThread的特点

  1. HandlerThread本质上是一个线程类,它继承了Thread
  2. HandlerThread有自己的内部Looper对象,可以进行looper循环
  3. 通过获取HandlerThread的looer对象传递给Handler对象,可以在handlerMessage方法中执行异步任务
  4. 优点是不会有堵塞,减少了对性能的消耗,缺点是不能同时进行多任务的处理,需要等待进行处理,处理效率较低。
  5. 与线程池注重并发不同,HandlerThread是一个串行队列,HandlerThread背后只有一个线程。

二、 HandlerThread源码解析

HandlerThread继承于线程,内部包含一个Looper,Looper在run方法中初始化并进入Loop循环

public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    Looper.loop();
}

外部使用时,利用这个Looper生成Handler,这样这个Handler的dispatchmessage方法就在子线程中运行了

public Looper getLooper() {
   return mLooper;
}
var handler:Handler = Handler(HandlerThread("123").looper){
       when(it.what){   
       }
   }

线程退出,需要调用quit函数,退出Loop循环

public boolean quit() {
       Looper looper = getLooper();
       if (looper != null) {
           looper.quit();
           return true;
       }
       return false;
   }

git代码

参考资料:
Android多线程:手把手教你使用HandlerThread HandlerThread源码