zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    假设用一个名为text的字符串向量存放文本文件的数据,其中的元素或者是一句话或者是一个用于表示段分隔的空字符串。将text中第一段全改为大写形式
    迭代器介绍
    从cin读入一组词并把它们存入一个vector对象,然后设法把所有词都改写为大写字母。
    标准库类型vector
    css 滤镜之AlphaImageLoader
    css设置背景图片自适应
    网易云音乐怎么免费下载付费歌曲
    font-family,font-size,color
    css设置图片居中、居左、居右
    数据库语句之建表、拷贝数据表
  • 原文地址:https://www.cnblogs.com/MrSaver/p/11262217.html
Copyright © 2011-2022 走看看