我们需要构造 2 道屏障,second
线程等待 first
屏障,third
线程等待 second
屏障。
first
线程会释放 first
屏障,而 second
线程会释放 second
屏障。
实例:
class Foo {
public boolean secondFinished = false;
public boolean thirdFinished = false;
public Object lock = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized(lock){
printFirst.run();
secondFinished=true;
lock.notifyAll();
}
// printFirst.run() outputs "first". Do not change or remove this line.
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized(lock){
while(secondFinished==false){
lock.wait();
}
printSecond.run();
thirdFinished=true;
lock.notifyAll();
}
// printSecond.run() outputs "second". Do not change or remove this line.
}
public void third(Runnable printThird) throws InterruptedException {
synchronized(lock){
while(thirdFinished==false){
lock.wait();
}
printThird.run();
}
// printThird.run() outputs "third". Do not change or remove this line.
}
}