1114. Print in Order

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
class Foo {

private final CountDownLatch latchA;
private final CountDownLatch latchB;

public Foo() {
this.latchA = new CountDownLatch(1);
this.latchB = new CountDownLatch(1);
}

public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
latchA.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {
latchA.await();
printSecond.run();
latchB.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
latchB.await();
printThird.run();
}

}
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
class Foo {

public Foo() {

}

private final Object lock = new Object();
private boolean shouldPrintFirst = true;
private boolean shouldPrintSecond = false;
private boolean shouldPrintThird = false;

public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
while (!shouldPrintFirst) {
lock.wait();
}
printFirst.run();
shouldPrintSecond = true;
shouldPrintFirst = false;
lock.notifyAll();
}
}

public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (!shouldPrintSecond) {
lock.wait();
}
printSecond.run();
shouldPrintThird = true;
shouldPrintSecond = false;
lock.notifyAll();
}
}

public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (!shouldPrintThird) {
lock.wait();
}
printThird.run();
shouldPrintFirst = true;
shouldPrintThird = false;
lock.notifyAll();
}
}

}

References

1114. Print in Order