• LeetCode:按序打印【1114】


    LeetCode:按序打印【1114】

    题目描述

    我们提供了一个类:

    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();
        }
    }
  • 相关阅读:
    sqlserver2012附加数据库2005版本时出现的问题
    jQuery实现评论还剩多少个字
    在mvc3中经常使用身份验证实现
    Windows Phone学习(1):棋子未动,先观全局
    使用jquery.pagination.js实现无刷新分页
    Javascript和JQuery中常用的随机数产生函数(很好用)
    网页打印样式设置(页眉,页脚,页边距)
    rdlc到设置宽度后自动换行(转)
    VSS忘记Admin密码和修改默认登陆用户
    解决jquery 修改onclick事件后IE兼容模式下立刻执行的问题
  • 原文地址:https://www.cnblogs.com/MrSaver/p/11262217.html
Copyright © 2020-2023  润新知