HandlerThread使用总结

来源:互联网 发布:nothing软件怎么样 编辑:程序博客网 时间:2024/09/21 06:47
  • HandlerThread实际上是一个Thread,但是在其内部却创建了Looper和MessageQueue等对象。
@Override    public void run() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll();        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();        mTid = -1;    }run方法里面mLooper创建完成后有个notifyAll(),getLooper()中有个wait(),这是为什么?因为mLooper在一个线程中执行,而handler实在UI线程初始化的,也就是说必须等mLooper创建完成,才能正确返回getLooper()。wait(),notify()就是为了解决这两个线程的同步问题。
  • 通过HandlerThread不但可以实现UI线程与子线程的通信同样也可以实现子线程之间的通信

  • HandlerThread在不需要使用的时候需要手动的回收掉
HandlerThread mHandlerThread = new HandlerThread("<TAG>");
mHandlerThread.start();
Handler mHandler = new Handler(mHandlerThread.getLooper()) {
public void handleMessage(Message mes) {

}

}

mHandlerThread.quit()      //exit the HandlerThread


0 0