[源码分析]Android消息机制之HandlerThread类

 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 }

 

转载于:https://www.cnblogs.com/patui/archive/2013/04/03/2998407.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值