打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
LeetCode:按序打印【1014】

题目描述

我们提供了一个类:

12345public 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"。

题目分析

  two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行,即two、three的前置任务(线程)均有1个,我们可以引入倒计时器,并初始化其值为1。

  这样,每当one完成后,two被唤醒,每当two完成后,three被唤醒。

Java题解

12345678910111213141516171819202122232425262728293031import java.util.concurrent.CountDownLatch; class Foo {     private CountDownLatch count_a = new CountDownLatch(1);    private CountDownLatch count_b = 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();        count_a.countDown();    }     public void second(Runnable printSecond) throws InterruptedException {        count_a.await();        // printSecond.run() outputs "second". Do not change or remove this line.        printSecond.run();        count_b.countDown();    }     public void third(Runnable printThird) throws InterruptedException {        count_b.await();        // printThird.run() outputs "third". Do not change or remove this line.        printThird.run();    }}
来源:https://www.icode9.com/content-4-366301.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
探索并发编程(四)——Java并发工具
Java的并发神器concurrent包详解(一)
ExecutorService 关闭 and 如何判断线程池中任务执行完毕
Java并发面试题
java 多线程 CountDownLatch用法
并发编程之:CountDownLatch
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服