java 打印线程的六种状态

java线程在运行的生命周期中有六种不同的状态。在给定的一个时刻,线程只能处于其中的一个状态。
那如何在代码中打印出这六种不同状态的线程呢?

借用Java并发编程艺术里面 java线程的六种状态的表格

java线程的六种状态

闲言少叙,上代码:

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
public class Main {
public static void main(String[] args) {
print("-------------线程的六种状态的打印---------------");
Thread sleepThread = new Thread(new SleepingRunnale());
/**
* 初始状态,线程被构建,但是还没有调用start()方法
* {@link Thread.State.NEW}
*/
print(sleepThread.getState().toString());
sleepThread.start();
/**
* 运行状态,
* {@link Thread.State.RUNNABLE}
*/
print(sleepThread.getState().toString());
sleepScond(1);
/**
* 此时线程内正执行sleep方法,可以在指定时间内返回,此时正处于超时等待状态
* {@link Thread.State.TIMED_WAITING}
*/
print(sleepThread.getState().toString());
sleepScond(3);
/**
* 线程执行完毕,终止状态
* {@link Thread.State.TERMINATED}
*/
print(sleepThread.getState().toString());

Thread waitThread = new Thread(new WaitRunnable());
Thread blockedThread = new Thread(new BlockedRunnable());

waitThread.start();
blockedThread.start();

sleepScond(1);
/**
* 由于waitThread获取了类对象的锁,blockedThread阻塞于锁
* {@link Thread.State.BLOCKED}
*/
print(blockedThread.getState().toString());

sleepScond(2);
/**
* 此时waitThread进入等待状态,释放了锁,blockedThread获得了锁,并处于TIMED_WAITING状态
* {@link Thread.State.WAITING}
*/
print(waitThread.getState().toString());
print("-------------Over~---------------");
}

private static class WaitRunnable implements Runnable {

@Override
public void run() {
synchronized (WaitRunnable.class) {
sleepScond(3);
try {
WaitRunnable.class.wait(); //3秒后进入等待状态,释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

private static class BlockedRunnable implements Runnable {

@Override
public void run() {
synchronized (WaitRunnable.class) {
sleepScond(3);
WaitRunnable.class.notify(); //通知锁释放
}
}
}

private static class SleepingRunnale implements Runnable {

@Override
public void run() {
sleepScond(3);
}
}

private static void print(String content) {
System.out.println(content);
}

private static void sleepScond(long seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

执行结果:

执行结果