forked from anton-liauchuk/java-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeadlock.java
More file actions
46 lines (40 loc) · 1.27 KB
/
Deadlock.java
File metadata and controls
46 lines (40 loc) · 1.27 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Deadlock {
private static final Object monitor1 = new Object();
private static final Object monitor2 = new Object();
public static void main(final String[] args) throws InterruptedException {
List<Thread> threads = new ArrayList<>();
threads.add(new Thread(Deadlock::handler1));
threads.add(new Thread(Deadlock::handler2));
Collections.shuffle(threads);
threads.get(0).start();
Thread.sleep(1000);
threads.get(1).start();
}
private static void handler1() {
synchronized (monitor1) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (monitor2) {
System.out.println("Hello from handler1");
}
}
}
private static void handler2() {
synchronized (monitor2) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (monitor1) {
System.out.println("Hello from handler2");
}
}
}
}