Skip to content

Commit f9d484e

Browse files
committed
DeadLock
1 parent 1372fb8 commit f9d484e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/chapter4/DeadLock.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package chapter4;
2+
3+
/**
4+
* Created by 13 on 2017/5/6.
5+
*/
6+
public class DeadLock extends Thread {
7+
protected Object tool;
8+
static Object fork1 = new Object();
9+
static Object fork2 = new Object();
10+
11+
public DeadLock(Object object) {
12+
this.tool = object;
13+
14+
if (tool == fork1) {
15+
this.setName("哲学家A");
16+
}
17+
if (tool == fork2) {
18+
this.setName("哲学家B");
19+
}
20+
}
21+
22+
public void run() {
23+
if (tool == fork1) {
24+
synchronized (fork1) {
25+
try {
26+
Thread.sleep(500);
27+
} catch (InterruptedException e) {
28+
e.printStackTrace();
29+
}
30+
31+
synchronized (fork2) {
32+
System.out.println("哲学家A开始吃饭了");
33+
}
34+
}
35+
}
36+
if (tool == fork2) {
37+
synchronized (fork2) {
38+
try {
39+
Thread.sleep(500);
40+
} catch (InterruptedException e) {
41+
e.printStackTrace();
42+
}
43+
44+
synchronized (fork1) {
45+
System.out.println("哲学家B开始吃饭了");
46+
}
47+
}
48+
}
49+
}
50+
51+
52+
public static void main(String args[]) throws InterruptedException {
53+
DeadLock 哲学家A = new DeadLock(fork1);
54+
DeadLock 哲学家B = new DeadLock(fork2);
55+
56+
哲学家A.start();
57+
哲学家B.start();
58+
59+
Thread.sleep(1000);
60+
}
61+
}

0 commit comments

Comments
 (0)