1 package android.os; 2 public class HandlerThread extends Thread { 3 private int mPriority;//线程优先级; 4 private int mTid = -1;//线程ID; 5 private Looper mLooper;//线程管理的消息队列; 6 public HandlerThread(String name) {//带名字的构造函数; 7 super(name); 8 mPriority = Process.THREAD_PRIORITY_DEFAULT; 9 } 10 public HandlerThread(String name, int priority) {//带名字和优先级的构造函数; 11 super(name); 12 mPriority = priority; 13 } 14 protected void onLooperPrepared() { 15 } 16 17 public void run() { 18 mTid = Process.myTid();//生成一个ID,应该是随机的; 19 Looper.prepare();//获取自身的Looper,也就是messageQenue的管理者; 20 synchronized (this) {//同步自己,因为外部可能会调用HandlerThread的成员方法getLooper(),导致不一致; 21 mLooper = Looper.myLooper();//返回自身的Looper; 22 notifyAll();//通知HandlerThread的成员方法getLooper(); 23 } 24 Process.setThreadPriority(mPriority);//设置优先级; 25 onLooperPrepared();//在消息喜欢之前做; 26 Looper.loop();//开始消息循环; 27 mTid = -1;//把线程ID设置为-1,应该是一个标志; 28 } 29 /** 30 * 通过Looper绑定Handler; 31 */ 32 public Looper getLooper() { 33 if (!isAlive()) {//判断线程是否已经存在; 34 return null; 35 } 36 synchronized (this) {//线程已经开始了,mLooper还没有建立,必须同步等待; 37 while (isAlive() && mLooper == null) { 38 try { 39 wait(); 40 } catch (InterruptedException e) { 41 } 42 } 43 } 44 return mLooper; 45 } 46 47 /** 48 * 退出消息循环; 49 */ 50 public boolean quit() { 51 Looper looper = getLooper();//获取当前的looper; 52 if (looper != null) { 53 looper.quit();//关闭消息循环; 54 return true; 55 } 56 return false; 57 } 58 59 /** 60 *获取线程的ID; 61 */ 62 public int getThreadId() { 63 return mTid; 64 } 65 }