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() 方法之后被执行。

 

示例 1:

输入: [1,2,3]
输出: "onetwothree"
解释: 
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。
示例 2:

输入: [1,3,2]
输出: "onetwothree"
解释: 
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。
 

注意:

尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。

你看到的输入格式主要是为了确保测试的全面性。

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

class Foo {

    private CountDownLatch countDownLatchA = new CountDownLatch(1);
    private CountDownLatch countDownLatchB = new CountDownLatch(1);

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        countDownLatchA.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        countDownLatchA.await();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        countDownLatchB.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        countDownLatchB.await();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 摘自郑总-《我的系列公开课-我在哪?》 人的层次分高低(格局大小之分) 越低越计较,越在乎别人对他的看法。活...
    懿瑜阅读 186评论 0 0
  • 好长时间没有失眠过了 今天竟然失眠了 ………………
    夏浅xq阅读 204评论 0 0
  • 最近知乎每天给我推送复读的各种消息,说实话,没有感触是不可能的 不可否认,你付出了多少,收获就是多少,整个高三的我...
    Tottoly阅读 354评论 2 2
  • 0.爱是恒久忍耐,又有恩慈 爱是不嫉妒 爱是不自夸,不张狂 不做害羞的事 不求自己的益处 不轻易发怒 不计算人的恶...
    基石之上阅读 838评论 0 3
  • 上回说到,古典音乐的了解要先掌握一个中心,两个基本点。敲黑板!复习:一个中心,两个基本点,最重要的是德奥音乐,它是...
    漫步云端的wendy阅读 695评论 0 4