-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy paththreads_37_deadlock.java
More file actions
73 lines (63 loc) · 1.74 KB
/
Copy paththreads_37_deadlock.java
File metadata and controls
73 lines (63 loc) · 1.74 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Deadlock. Two threads, two locks on different objects in different order.
Thread 1 locks on 2 then 1, thread 2 locks on 1 then 2. In lock 1 assign to var a, in lock 2 assign to b.
Print a and b inside inner lock, and after inner lock.
See multiple states and some deadlocks.
Possible messages:
22 22 33 33
22 23 33 33
33 33 22 22
33 23 22 22
deadlock
*/
public class threads_37_deadlock {
public static void main(String[] args) {
Thread thread2 = new Thread(new MyRunnable2(2));
thread2.start();
Thread thread3 = new Thread(new MyRunnable3(3));
thread3.start();
try {
thread2.join();
thread3.join();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Done!");
}
}
class MyRunnable2 implements Runnable {
static int a;
static int b;
static Object monitor1 = new Object();
static Object monitor2 = new Object();
int id;
MyRunnable2(int id) {
this.id = id;
}
public void run() {
synchronized(monitor1) {
a = id;
synchronized(monitor2) {
b = id;
System.out.println("Thread" + id + " inner lock: a = " + a + ", b = " + b);
}
System.out.println("Thread" + id + " outer lock: a = " + a + ", b = " + b);
}
}
}
class MyRunnable3 implements Runnable {
int id;
MyRunnable3(int id) {
this.id = id;
}
public void run() {
synchronized(MyRunnable2.monitor2) {
MyRunnable2.b = id;
synchronized(MyRunnable2.monitor1) {
MyRunnable2.a = id;
System.out.println("Thread" + id + " inner lock: a = " + MyRunnable2.a + ", b = " + MyRunnable2.b);
}
System.out.println("Thread" + id + " outer lock: a = " + MyRunnable2.a + ", b = " + MyRunnable2.b);
}
}
}