java-doc-suspend和resume

suspend和resume

容易写出死锁的代码 。不在建议使用

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
public class LearnSuspend1 {
public static Object iceCream = null;

public static void main(String[] args) throws Exception {
LearnSuspend1 sup = new LearnSuspend1();
sup.suspendResumeTest();
//sup.test2_SyncDeadLock();
//sup.test3_OrderDeadLock();
}

// 正常运行
public void suspendResumeTest() throws Exception {
// 启动线程
Thread consumerThread = new Thread(() -> {
if (iceCream == null) {
System.out.println("没有冰激凌, 小朋友不开心, 等待...");
Thread.currentThread().suspend();
}

System.out.println("小朋友买到冰激凌, 开心回家");
});
consumerThread.start();
Thread.sleep(3000L); // 3秒之后
iceCream = new Object(); //店员做好了冰激凌
consumerThread.resume(); //通知小朋友
System.out.println("通知小朋友");
}

// 死锁1
public void test2_SyncDeadLock() throws Exception {
//开启一个线程, 代表小朋友
Thread consumerThread = new Thread(() -> {
if (iceCream == null) { // 若没冰激凌
System.out.println("没有冰激凌, 小朋友不开心, 等待...");
synchronized (this.iceCream) { // 小朋友把钥匙拿着
Thread.currentThread().suspend(); //睡着了
}
}
System.out.println("小朋友买到冰激凌, 开心回家");
});
consumerThread.start();
Thread.sleep(3000L); // 3秒之后,
iceCream = new Object(); // 店员做了一个冰激凌
synchronized (this) { // 拿到小朋友加的钥匙, 才能进去叫他
consumerThread.resume();
}
System.out.println("通知小朋友");
}

// 死锁2
public void test3_OrderDeadLock() throws Exception {
//开启一个线程, 代表小朋友
Thread consumerThread = new Thread(() -> {
if (iceCream == null) { // 若没冰激凌
try {
Thread.sleep(5000L); // 模拟小朋友出去玩
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("没有冰激凌, 小朋友不开心, 等待...");
Thread.currentThread().suspend(); // suspend在resume之前
}
System.out.println("小朋友买到冰激凌, 开心回家");
});
consumerThread.start();
Thread.sleep(3000L); // 3秒之后
iceCream = new Object(); //店员做了一个冰激凌
consumerThread.resume(); //喊了一声, 小朋友根本没在家睡觉
System.out.println("通知小朋友");
}
}