-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrderPrinter.java
100 lines (81 loc) · 2.56 KB
/
OrderPrinter.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package org.sean.concurrency;
/***
* 1114. Print in Order
*/
public class OrderPrinter {
private volatile int order = 0;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
private synchronized void updateOrder() {
++order;
}
public OrderPrinter() {}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
updateOrder();
synchronized (lock1) {
lock1.notify();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock1) {
while (order != 1) {
lock1.wait();
}
printSecond.run();
updateOrder();
}
synchronized (lock2) {
lock2.notify();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (lock2) {
while (order != 2) {
lock2.wait();
}
updateOrder();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
private void print(String str) {
System.out.print(str);
}
public static void main(String[] args) throws InterruptedException {
OrderPrinter printer = new OrderPrinter();
Thread t1 =
new Thread(
() -> {
try {
printer.first(() -> printer.print("first"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.join();
Thread t2 =
new Thread(
() -> {
try {
printer.second(() -> printer.print("second"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t2.join();
Thread t3 =
new Thread(
() -> {
try {
printer.third(() -> printer.print("third"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t3.join();
t3.start();
t2.start();
t1.start();
}
}