HandlerThread分析

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

1。看source code (省略部分)

 1 public class HandlerThread extends Thread {
 2    
 3     int mTid = -1;
 4     Looper mLooper;
 5 
 6       /**
 7      * Call back method that can be explicitly overridden if needed to execute some
 8      * setup before Looper loops.
 9      */
10     protected void onLooperPrepared() {                                                  //注意这个方法
11     }
12    
13 
14     public void run() {
15         mTid = Process.myTid();
16         Looper.prepare();
17         synchronized (this) {
18             mLooper = Looper.myLooper();
19             notifyAll();
20         }
21         Process.setThreadPriority(mPriority);
22         onLooperPrepared();                                                            //调用上面的方法
23         Looper.loop();
24         mTid = -1;
25     }
26     
27     /**
28      * This method returns the Looper associated with this thread. If this thread not been started
29      * or for any reason is isAlive() returns false, this method will return null. If this thread 
30      * has been started, this method will block until the looper has been initialized.  
31      * @return The looper.
32      */
33     public Looper getLooper() {
34         if (!isAlive()) {
35             return null;
36         }
37         
38         // If the thread has been started, wait until the looper has been created.
39         synchronized (this) {
40             while (isAlive() && mLooper == null) {
41                 try {
42                     wait();
43                 } catch (InterruptedException e) {
44                 }
45             }
46         }
47         return mLooper;
48     }
49     
50 }