多线程执行屏障问题

我们需要构造 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.
    }
}
发布了49 篇原创文章 · 获赞 7 · 访问量 4399

猜你喜欢

转载自blog.csdn.net/qq_37822034/article/details/103950424