-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy paththreads_38_two_locks.java
More file actions
78 lines (65 loc) · 1.81 KB
/
Copy paththreads_38_two_locks.java
File metadata and controls
78 lines (65 loc) · 1.81 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
74
75
76
77
78
/*
Two threads, two locks on different objects, but not nested. No deadlocks.
Thread 1: lock 1, assign and print a, lock 2 - assign and print b.
Thread 2: lock 2, assign and print b, lock 1 - assign and print a.
See multiple states, but no deadlocks.
Message order: all permutations:
- 1 1 2 2
- 1 2 1 2
- 1 2 2 1
- 2 1 1 2
- 2 1 2 1
- 2 2 1 1
Since for each thread run the actual output may be very different, there are 38 solutions.
*/
public class threads_38_two_locks {
public static void main(String[] args) {
Thread thread2 = new Thread(new MyRunnable2(2));
Thread thread3 = new Thread(new MyRunnable3(3));
thread2.start();
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;
System.out.println("Thread" + id + " outer lock: a = " + a + ", b = " + b);
}
synchronized(monitor2) {
b = id;
System.out.println("Thread" + id + " inner 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;
System.out.println("Thread" + id + " outer lock: a = " + MyRunnable2.a + ", b = " + MyRunnable2.b);
}
synchronized(MyRunnable2.monitor1) {
MyRunnable2.a = id;
System.out.println("Thread" + id + " inner lock: a = " + MyRunnable2.a + ", b = " + MyRunnable2.b);
}
}
}