1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
| //继承Thread,本身就是线程
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
//内部持有looper
Looper mLooper;
//内部持有handler
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
//Process是进程的帮助类,可提供进程信息
mTid = Process.myTid();
//初始化loop
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
//完成之后唤醒需要使用looper的线程,主要是针对getLooper()方法
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//开启循环
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// 确保Looper一定能实例化
synchronized (this) {
// 自旋
while (isAlive() && mLooper == null) {
try {
// 阻塞调用的线程,直到run方法中looper初始化完成
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
//初始化内部Handler,但是外部不能调用此方法
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
//关闭
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
//安全关闭
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
//返回线程id
public int getThreadId() {
return mTid;
}
}
|