Решение
class Foo {
private final Object lock = new Object();
private int stage = 1;
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
while (stage != 1) {
lock.wait();
}
printFirst.run();
stage = 2;
lock.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (stage != 2) {
lock.wait();
}
printSecond.run();
stage = 3;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (stage != 3) {
lock.wait();
}
printThird.run();
}
}
}