-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeadlockSample.java
59 lines (53 loc) · 1.84 KB
/
DeadlockSample.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Java example program on thread deadlock
public class DeadLockSample {
// Simulates global resources shared by multiple threads
String R1 = "R1";
String R2 = "R2";
Thread T1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Starting T1");
// Acquired R1
synchronized (R1) {
try {
// Sleep is added to make deadlock predictable
// One second delay ensures that the other thread
// acquires lock on R2!
Thread.sleep(100);
} catch (Exception ex) {
}
synchronized (R2) {
System.out.println("Acquired both!");
}
}
// If we reach here, no deadlock!
System.out.println("Completed T1");
}
});
Thread T2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Starting T2");
synchronized (R2) {
try {
// Sleep is added to make deadlock predictable
// One second delay ensures that the other thread
// acquires lock on R1!
Thread.sleep(100);
} catch (Exception ex) {
}
synchronized (R1) {
System.out.println("Acquired both!");
}
}
// If we reach here, no deadlock!
System.out.println("Completed T2");
}
});
// Java example program on thread deadlock
public static void main(String[] args) {
DeadLockSample ds = new DeadLockSample();
ds.T1.start();
ds.T2.start();
}
}