[LeetCode]1114. 按序打印(并发)

题目

我们提供了一个类:

public class Foo {
  public void one() { print("one"); }
  public void two() { print("two"); }
  public void three() { print("three"); }
}
三个不同的线程将会共用一个 Foo 实例。

线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

使用synchronzed锁+while(条件)的方式,使用线程的等待通知实现。
second方法等待firstFinished;third方法等待secondFinished。

代码

class Foo {

    private Object obj = new Object();
    private boolean firstFinished = false;
    private boolean secondFinished = false;

    public Foo() {
        
    }

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

    public void second(Runnable printSecond) throws InterruptedException {
        
        // printSecond.run() outputs "second". Do not change or remove this line.
        synchronized(obj){
            while(!firstFinished){
                obj.wait();
            }

            printSecond.run();
            secondFinished = true;
            obj.notifyAll();
        }
    }

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

            printThird.run();
        }       
    }
}

posted on   coding_gaga  阅读(114)  评论(0编辑  收藏  举报

努力加载评论中...
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示