美文网首页
小知识:HandlerThread

小知识:HandlerThread

作者: 一个追寻者的故事 | 来源:发表于2020-09-13 10:57 被阅读0次

本篇内容很简单,纯属记录方便日后记忆。

What : 是一个实现了 Handler 机制的 Thread。「A Thread that has a Looper.」

使用:

class SecondActivity : AppCompatActivity() {
  private val handlerThread = HandlerThread("ThreadName#HandlerThread")
  lateinit var h : Handler

  override fun onCreate(savedInstanceState: Bundle?) {
    ...
    // start
    handlerThread.start()

    // blocking
    h = Handler(handlerThread.looper)

    h.post {
        // 在子线程中运行

        // do something wasting time
        try {
            TimeUnit.MILLISECONDS.sleep(200)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        Log.e(SecondActivity::class.java.name, Thread.currentThread().name)
    }

  }
}

运行结果:

ThreadName#HandlerThread

在开启的子线程 Thread 中,默认是没有开启Handler循环机制的,需要我们手动调用 Looper#prepareLooper#loop,来开始Looper消息循环,不断接受其他线程发送的消息,然后分发处理。HandlerThread 是对上述操作的简单封装,HanderThread 的实现比较简单,一看就知道了:

public class HandlerThread extends Thread {
    ...
    @Override
    public void run() {
        ...
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Looper.loop();
        ...
    }

    /**
      这个方法返回这个线程关联的Looper对象,如果这个线程还没有开启,则直接返回null
      如果线程已经开启,这个方法将阻塞,直到Looper被初始化,所有wait的线程将被唤醒。
    */
    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;
    }

}

相关文章

网友评论

      本文标题:小知识:HandlerThread

      本文链接:https://www.haomeiwen.com/subject/dnkbektx.html