-
Notifications
You must be signed in to change notification settings - Fork 0
/
FooBar.java
55 lines (41 loc) · 1.17 KB
/
FooBar.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
package org.sean.concurrency;
/***
* 1115 Print FooBar Alternately
*/
public class FooBar {
private int n;
private volatile int order = 0;
private final Object lock = new Object();
public FooBar(int n) {
this.n = n;
}
private synchronized void update() {
++order;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
while (order % 2 != 0) {
lock.wait();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
update();
lock.notify();
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
while (order % 2 == 0) {
lock.wait();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
update();
lock.notify();
}
}
}
}