Leetcode 1114. 按序打印 Java多线程编程

Leetcode 1114. 按序打印 Java多线程编程_第1张图片

Leetcode 1114. 按序打印 Java多线程编程_第2张图片 

由于三个线程只需要按序打印一次,采用Java并发编程艺术最简单的等待通知机制。

class Foo {

    private boolean isPrintSecond = false;
    private boolean isPrintThird = false;
    private Object lock = new Object();
    public Foo() {}

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        synchronized(lock){
            printFirst.run();
            isPrintSecond = true;
            lock.notifyAll();
        }
    }

    public void second(Runnable printSecond) throws InterruptedException {
        
        synchronized(lock){
            while(!isPrintSecond){
                lock.wait();
            }
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            isPrintThird = true;
            lock.notifyAll();

        }
    }

    public void third(Runnable printThird) throws InterruptedException {
        synchronized(lock){
            while(!isPrintThird){
                lock.wait();
            }
             // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
        }
    }
}

 

你可能感兴趣的:(算法)