1114-按序打印

前言

LeetCode题库多线程部分按序打印多线程

咱们提供了一个类:异步

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

示例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"。

提示:
尽管输入中的数字彷佛暗示了顺序,可是咱们并不保证线程在操做系统中的调度顺序。设计

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

解题思路

本题的题目其实很容易,题目描述的很清楚。我选择的是使用while死循环结合一个int变量控制对应的线程进行打印。须要注意int变量须要使用volatile修饰确保其的可见性和有序性。three

实现代码

/**
 * 1114. 按序打印
 * @author NULL
 * @see <a href="https://leetcode-cn.com/problems/print-in-order/">1114. 按序打印</a>
 * @date 2019-09-08
 */
class Foo {
    /**
     * 当前应该打印的线程
     */
    private volatile int status = 1;

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        while(status==1){
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            status=2;
        }
    }

    public void second(Runnable printSecond) throws InterruptedException {
        while (status!=2){
            // 此处不等于2则死循环等待
        }
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        status=3;
    }

    public void third(Runnable printThird) throws InterruptedException {
        while (status!=3){
            // 此处不等于3则死循环等待
        }
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
        status=1;
    }

}