forked from ZHENFENG13/concurrent-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadLock.java
More file actions
61 lines (51 loc) · 1.44 KB
/
DeadLock.java
File metadata and controls
61 lines (51 loc) · 1.44 KB
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
package chapter4;
/**
* Created by 13 on 2017/5/6.
*/
public class DeadLock extends Thread {
protected Object tool;
static Object fork1 = new Object();
static Object fork2 = new Object();
public DeadLock(Object object) {
this.tool = object;
if (tool == fork1) {
this.setName("哲学家A");
}
if (tool == fork2) {
this.setName("哲学家B");
}
}
public void run() {
if (tool == fork1) {
synchronized (fork1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (fork2) {
System.out.println("哲学家A开始吃饭了");
}
}
}
if (tool == fork2) {
synchronized (fork2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (fork1) {
System.out.println("哲学家B开始吃饭了");
}
}
}
}
public static void main(String args[]) throws InterruptedException {
DeadLock 哲学家A = new DeadLock(fork1);
DeadLock 哲学家B = new DeadLock(fork2);
哲学家A.start();
哲学家B.start();
Thread.sleep(1000);
}
}