-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAlternatePrintFooBar.java
58 lines (37 loc) · 1.13 KB
/
AlternatePrintFooBar.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
package multithreading;
/**
* @Author: Wenhang Chen
* @Description:
* @Date: Created in 17:38 4/4/2020
* @Modified by:
*/
public class AlternatePrintFooBar {
private int n;
private final static Object lock = new Object();
private boolean fooTurn = true;
public AlternatePrintFooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
if (!fooTurn) lock.wait();
fooTurn = false;
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
lock.notifyAll();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
if (fooTurn) lock.wait();
fooTurn = true;
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
lock.notifyAll();
}
}
}
}