一图讲解状态的含义和变化
展示线程的NEW、RUNNABLE、Terminated状态
package threadcoreknowledge.sixstates;
/**
* 描述: 展示线程的NEW、RUNNABLE、Terminated状态。即使是正在运行,也是Runnable状态,而不是Running。
*/
public class NewRunnableTerminated implements Runnable {
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
//打印出NEW的状态
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出RUNNABLE的状态,即使是正在运行,也是RUNNABLE,而不是RUNNING
System.out.println(thread.getState());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出TERMINATED状态
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
打印结果
NEW
RUNNABLE
0
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
RUNNABLE
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
TERMINATED
展示Blocked, Waiting, TimedWaiting
package threadcoreknowledge.sixstates;
/**
* 描述: 展示Blocked, Waiting, TimedWaiting
*/
public class BlockedWaitingTimedWaiting implements Runnable{
public static void main(String[] args) {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出Timed_Waiting状态,因为正在执行Thread.sleep(1000);
System.out.println(thread1.getState());
//打印出BLOCKED状态,因为thread2想拿得到sync()的锁却拿不到
System.out.println(thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出WAITING状态,因为执行了wait()
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
打印结果
阻塞状态
一般习惯而言,Blocked
(被阻塞),Waiting
(等待)、Timed_waiting
(计时等待)都被称为阻塞状态。
Blocked
:进入synchronized方法或代码块,但拿不到锁。