HandlerThread

字数 102阅读 41

HandlerThead继承自Thead,其内部为用户初始化了一个Looper,这样当在子线程中使用Handler时可直接使用HandlerThread这个线程,优点如下:

  • 省去自己初始化Looper麻烦。
  • 在获取这个Looper时如果Looper为空,也就是说还没准备好时程序会一直阻塞,知道Looper不为null。

代码如下:

public class HandlerThread extends Thread {
   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;
   }
   
   /**
    * This method returns the Looper associated with this thread. If this thread not been started
    * or for any reason is isAlive() returns false, this method will return null. If this thread 
    * has been started, this method will block until the looper has been initialized.  
    * @return The looper.
    */
   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;
   }

推荐阅读更多精彩内容