Skip to content

Commit 2f6902c

Browse files
committed
update
1 parent b8e8792 commit 2f6902c

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

Android 消息机制.md

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,23 +63,44 @@ Android 消息机制
6363
```
6464

6565
#### HandlerThread : 自带 looper,handler ,Messager 的子线程;
66-
> 同步的
67-
68-
HandlerThread 源码中,利用 wait 和 notifyAll()的方法,控制了UI线程 和 开启的子线程同步性;
66+
> HandlerThread 源码中,利用 wait 和 notifyAll()的方法,控制了UI线程 和 开启的子线程同步性;
67+
> 会自主创建线程 , looper, handler 和 messageQueue;处理消息,以及当任务执行完成后就会自动销毁;
6968
7069
使用方法:
7170
```java
7271
HandlerThread mht = new HandlerThread("ThreadName");
72+
//创建实例对象,参数就是当前线程的名字;
7373
mht.start();
7474
Handler UIhandler = new Handler(mht.getLooper()){
7575
@Override
7676
public void handleMessage(Message msg)
7777
{
78-
//这个 message 就是线程中的Message
78+
//这个 message 就是线程中的MessageQueue 消息队列
7979
}
8080
}
8181
};
8282
```
8383

84-
创建 HandlerThread 对象, 构造函数输入该线程的名字,然后获取子线程的 looper 创建 Handler ,创建 HanderMessage 进行逻辑处理;取出来的消息是子线程的消息;
84+
创建 HandlerThread 对象, 构造函数输入该线程的名字,调用 start 方法,运行其重写的 run 方法,创建 looper 和 消息队列,然后获取子线程的 looper 创建 Handler ,创建 HanderMessage 进行逻辑处理;取出来的消息是子线程中待处理的消息;
85+
可以其中进行耗时的请求操作,操作完成后,可以通过 UI线程的 Handler 发送完成消息;
86+
87+
##### 同步的维持:
88+
```java
89+
@Override
90+
public void run() {
91+
mTid = Process.myTid();
92+
Looper.prepare();
93+
synchronized (this) {
94+
mLooper = Looper.myLooper();
95+
notifyAll(); //唤醒等待线程
96+
}
97+
Process.setThreadPriority(mPriority);
98+
onLooperPrepared();
99+
Looper.loop();
100+
mTid = -1;
101+
}
102+
```
103+
锁住当前对象,保持同步
85104

105+
##### 获取Looper 的时候为什么要延时?
106+
因为创建 Looper 是再子线程中 需要用 wait 命令 等到 Looper 的创建完成;才能从UI线程中获取才不会出错;

0 commit comments

Comments
 (0)