关键方法

3.1 run()方法

处理线程中执行的逻辑,如果继承Thread类则必须重写该方法.

3.2 start()方法

//方法是加了锁的。
//原因是避免开发者在其它线程调用同一个Thread实例的这个方法,从而尽量避免抛出异常。
//这个方法之所以能够执行我们传入的Runnable里的run()方法,
//是应为JVM调用了Thread实例的run()方法。

public synchronized void start() {

//检查线程状态是否为0,为0表示是一个新状态,即还没被start()过。不为0就抛出异常。
//就是说,我们一个Thread实例,我们只能调用一次start()方法。
if (threadStatus != 0 || started)
throw new IllegalThreadStateException();
从这里开始才真正的线程加入到ThreadGroup组里。
//再重复一次,前面只是把nUnstartedThreads这个计数器进行了增量,并没有添加线程。
//同时,当线程启动了之后,nUnstartedThreads计数器会-1。因为就绪状态的线程少了一条啊!
group.add(this);

started = false;
try {
//Native方法。这里交由JVM处理,会调用Thread实例的run()方法。
nativeCreate(this, stackSize, daemon);
started = true;
} finally {
try {
if (!started) {
//如果没有被启动成功,Thread将会被移除ThreadGroup,
//同时,nUnstartedThreads计数器又增量1了
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
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
3.3 setPriority()方法
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
// Android-changed: Improve exception message when the new priority
// is out of bounds.
throw new IllegalArgumentException("Priority out of range: " + newPriority);
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
synchronized(this) {
this.priority = newPriority;
if (isAlive()) {
nativeSetPriority(newPriority);
}
}
}
}
// nativeSetPriority() 才是真正的给执行线程设置优先级, 所以如果不调用 setPriority() 方法, 创建 Thread 对象的时候, 其实压根就没有把线程设置优先级, 只是给 Thread 对象设置变量.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
3.4 interrupt()方法
public void interrupt() {
//中断其他线程,需要先判断当前线程是否允许修改其他线程
if (this != Thread.currentThread())
checkAccess();

synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
nativeInterrupt();//nativa方法 终端线程
b.interrupt(this);
return;
}
}
nativeInterrupt();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Interruptible是神马我没看到。

join方法


线程安全,
wait(0)方法,表示释放锁,线程进入等待状态
————————————————

posted @ 2019-08-23 22:07  李艳艳665  阅读(124)  评论(0编辑  收藏  举报