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