Skip to content

Commit 2d79fbc

Browse files
ThreadLifeCycle
1 parent e3547e7 commit 2d79fbc

File tree

4 files changed

+99
-0
lines changed

4 files changed

+99
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package threadlifecycle;
2+
3+
/**
4+
* 展示Blocked,Waited,TimedWaiting
5+
* 一般习惯将这三种都称之为阻塞状态
6+
*
7+
* @Author: zzStar
8+
* @Date: 10-16-2020 19:37
9+
*/
10+
public class BlockedWaitedTimedWaiting implements Runnable {
11+
public static void main(String[] args) throws InterruptedException {
12+
BlockedWaitedTimedWaiting blockedWaitedTimedWaiting = new BlockedWaitedTimedWaiting();
13+
//两个线程公用一个实例
14+
Thread thread1 = new Thread(blockedWaitedTimedWaiting);
15+
thread1.start();
16+
Thread thread2 = new Thread(blockedWaitedTimedWaiting);
17+
thread2.start();
18+
Thread.sleep(5);
19+
// TIMED_WAITING,因为正在执行Thread.sleep(1000)
20+
System.out.println(thread1.getState());
21+
// BLOCKED,因为thread2想拿得到sync()🔒却拿不到
22+
System.out.println(thread2.getState());
23+
Thread.sleep(1500);
24+
// WAITING
25+
System.out.println(thread1.getState());
26+
thread1.interrupt();
27+
thread2.interrupt();
28+
}
29+
30+
@Override
31+
public void run() {
32+
syn();
33+
}
34+
35+
// run方法里要实现一个线程获取到,一个等待
36+
private synchronized void syn() {
37+
try {
38+
Thread.sleep(1000);
39+
wait();
40+
} catch (InterruptedException e) {
41+
e.printStackTrace();
42+
}
43+
}
44+
}
325 KB
Loading
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package threadlifecycle;
2+
3+
/**
4+
* 线程的六种状态总结
5+
*
6+
* @Author: zzStar
7+
* @Date: 10-16-2020 19:03
8+
*/
9+
public class LifeCycleSummary {
10+
/**
11+
* 一图胜千言
12+
* 左侧是从上到下的一条线,右侧经过runnable互相转换
13+
*/
14+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package threadlifecycle;
2+
3+
/**
4+
* 展示三种状态
5+
* <p>
6+
* 即使是正在运行,也是Runnable状态,而不是Running
7+
*
8+
* @Author: zzStar
9+
* @Date: 10-16-2020 19:04
10+
*/
11+
public class NewRunnableTerminated implements Runnable {
12+
public static void main(String[] args) {
13+
Thread thread = new Thread(new NewRunnableTerminated());
14+
//NEW
15+
System.out.println(thread.getState());
16+
thread.start();
17+
//RUNNABLE
18+
System.out.println(thread.getState());
19+
try {
20+
Thread.sleep(10);
21+
} catch (InterruptedException e) {
22+
e.printStackTrace();
23+
}
24+
//RUNNABLE!!!
25+
System.out.println(thread.getState());
26+
try {
27+
Thread.sleep(10);
28+
} catch (InterruptedException e) {
29+
e.printStackTrace();
30+
}
31+
//TERMINATED
32+
System.out.println(thread.getState());
33+
}
34+
35+
@Override
36+
public void run() {
37+
for (int i = 0; i < 1000; i++) {
38+
System.out.println(i);
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)