-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathPrint in Order.java
44 lines (37 loc) · 1.1 KB
/
Print in Order.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
import java.util.concurrent.atomic.AtomicInteger;
class Foo {
private Object lock;
private AtomicInteger counter;
public Foo() {
this.lock = new Object();
this.counter = new AtomicInteger(0);
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
synchronized (lock) {
printFirst.run();
this.counter.incrementAndGet();
this.lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
synchronized (lock) {
while (this.counter.get() != 1) {
this.lock.wait();
}
printSecond.run();
this.counter.incrementAndGet();
this.lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
synchronized (lock) {
while (this.counter.get() != 2) {
this.lock.wait();
}
printThird.run();
}
}
}