0%

线程的生命周期

Java中线程的状态分为6种,分别是new、runnable、blocked、waiting、timed_waiting、terminated。

状态间的转换图示

thread.jpg

代码演示

new、runnable、terminated状态如下:

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

/**
* @author gelong
* @date 2020/6/11 21:17
*/
public class NewRunnableTerminated implements Runnable {

public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new NewRunnableTerminated());
System.out.println(thread.getState());
thread.start();
Thread.sleep(1000);
System.out.println(thread.getState());
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(i);
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

states.jpg

blocked、waiting、timed_waiting状态如下:

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

/**
* @author gelong
* @date 2020/6/11 21:43
*/
public class BlockedWaitingTimedWaiting implements Runnable {

public static void main(String[] args) throws InterruptedException {
Runnable runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
Thread.sleep(500);
System.out.println(thread1.getName() + " " + thread1.getState());
System.out.println(thread2.getName() + " " + thread2.getState());
Thread.sleep(1200);
System.out.println(thread1.getName() + " " + thread1.getState());
}

@Override
public void run() {
sync();
}

private synchronized void sync() {
try {
Thread.sleep(1000);
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

states2.jpg