HandlerThread

2017-09-26  本文已影响33人  打不死的小强qz

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

代码如下:

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;
   }
上一篇下一篇

猜你喜欢

热点阅读