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