Skip to content

Commit e49479c

Browse files
committed
add deadlock example
1 parent 9e7e012 commit e49479c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Concurrency/Deadlock.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// ref:
2+
// https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
3+
// https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
4+
5+
public class Deadlock {
6+
static class Friend {
7+
private final String name;
8+
9+
public Friend(String name) {
10+
this.name = name;
11+
}
12+
13+
public String getName() {
14+
return this.name;
15+
}
16+
17+
public synchronized void bow(Friend bower) {
18+
System.out.format("%s: %s"
19+
+ " has bowed to me!%n",
20+
this.name, bower.getName());
21+
bower.bowBack(this);
22+
}
23+
24+
public synchronized void bowBack(Friend bower) {
25+
System.out.format("%s: %s"
26+
+ " has bowed back to me!%n",
27+
this.name, bower.getName());
28+
}
29+
}
30+
31+
public static void main(String[] args) throws Exception{
32+
final Friend alphonse = new Friend("Alphonse");
33+
final Friend gaston = new Friend("Gaston");
34+
new Thread(new Runnable() {
35+
public void run() { alphonse.bow(gaston); }
36+
}).start();
37+
// Thread.sleep(10000);
38+
new Thread(new Runnable() {
39+
public void run() { gaston.bow(alphonse); }
40+
}).start();
41+
}
42+
}

0 commit comments

Comments
 (0)