-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathDeadLock.java
More file actions
53 lines (48 loc) · 1.41 KB
/
Copy pathDeadLock.java
File metadata and controls
53 lines (48 loc) · 1.41 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
package ch4.s5;
public class DeadLock extends Thread {
protected Object tool;
static Object fork1 = new Object();
static Object fork2 = new Object();
public DeadLock(Object obj){
this.tool = obj;
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);
}
}