leetcode多线程之按序打印

时间:2022-07-24
本文章向大家介绍leetcode多线程之按序打印,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文主要记录一下leetcode多线程之按序打印

题目

我们提供了一个类:
​
public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}
​
三个不同的线程将会共用一个 Foo 实例。
​
    线程 A 将会调用 first() 方法
    线程 B 将会调用 second() 方法
    线程 C 将会调用 third() 方法
​
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
​
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

使用juc包的CountDownLatch

class Foo {
​
    CountDownLatch second = new CountDownLatch(1);
    CountDownLatch third = new CountDownLatch(1);
​
    public Foo() {
        
    }
​
    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        second.countDown();
        
    }
​
    public void second(Runnable printSecond) throws InterruptedException {
        second.await();
        printSecond.run();
        third.countDown();
    }
​
    public void third(Runnable printThird) throws InterruptedException {
        third.await();
        printThird.run();
    }
}

小结

这里是固定要按first先执行,而后second,再third方法,这里使用了CountDownLatch,比起object的wait notify之类用起来简单一点

doc