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;
    }

}
相關文章
相關標籤/搜索