-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFoo.java
80 lines (70 loc) · 2.23 KB
/
Foo.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
package thread.leetcode1114;
/**
* 按序打印
* LeetCode 1114 https://leetcode-cn.com/problems/print-in-order/
*
* @author yangyi 2021年05月02日15:18:19
*/
public class Foo {
private boolean firstFinish = false;
private boolean secondFinish = false;
private final Object lock = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinish = true;
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (!firstFinish) {
lock.wait();
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinish = true;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (!secondFinish) {
lock.wait();
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
lock.notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Foo foo = new Foo();
Runnable printFirst = () -> System.out.println("first");
Runnable printSecond = () -> System.out.println("second");
Runnable printThird = () -> System.out.println("third");
new Thread(() -> {
try {
foo.third(printThird);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
foo.first(printFirst);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
foo.second(printSecond);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}