-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathDeadlock.java
38 lines (29 loc) · 1.08 KB
/
Deadlock.java
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
package by.andd3dfx.multithreading;
import lombok.AllArgsConstructor;
/**
* Example from JDK: http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
*
* @see <a href="https://youtu.be/xuWU_6JTXi4">Video solution</a>
*/
public class Deadlock {
@AllArgsConstructor
public class Friend {
private final String name;
public synchronized void bow(Friend bower) {
System.out.printf("%s: %s has bowed to me!%n", name, bower.name);
bower.bowBack(this);
}
private synchronized void bowBack(Friend bower) {
System.out.printf("%s: %s has bowed back to me!%n", name, bower.name);
}
}
public void makeDeadlock() {
Friend alphonse = new Friend("Alphonse");
Friend gaston = new Friend("Gaston");
Thread thread1 = new Thread(() -> alphonse.bow(gaston));
Thread thread2 = new Thread(() -> gaston.bow(alphonse));
thread1.start();
thread2.start();
while (thread1.isAlive() || thread2.isAlive()) ;
}
}