1.问题描述
2.解决办法
构造屏障:构造两道屏障,second 线程等待 first 屏障,third 线程等待 second 屏障。first 线程会释放 first 屏障,而 second 线程会释放 second 屏障.
Java 中,我们使用线程等待的方式实现执行屏障,使用释放线程等待的方式实现屏障消除。
我们使用一个 Ojbect 对象 lock 实现所有执行屏障的锁对象,两个布尔型对象 firstFinished,secondFinished 保存屏障消除的条件。
数累加:定义一个count 用于计数,只有当count达成某一条件才能执行当前线程
3.代码实现
class Foo {
private boolean firstFinished;
private boolean secondFinished;
private Object lock = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinished = true;
lock.notifyAll(); //object类中方法用于唤醒所有在此对象监视器上等待的线程。
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (!firstFinished) {
lock.wait();
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinished = true;
lock.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (!secondFinished) {
lock.wait();
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
}