ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode:按序打印【1014】

2019-07-29 09:52:40  阅读:490  来源: 互联网

标签:run void two LeetCode 线程 three 按序 1014 public


LeetCode:按序打印【1014】

题目描述

我们提供了一个类:

1 2 3 4 5 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"。

 

题目分析

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

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

 

Java题解

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 import 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();     } }

标签:run,void,two,LeetCode,线程,three,按序,1014,public
来源: https://www.cnblogs.com/MrSaver/p/11262217.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有