https://leetcode-cn.com/problems/print-in-order/
我們提供了一個(gè)類:
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三個(gè)不同的線程將會(huì)共用一個(gè) Foo 實(shí)例。
線程 A 將會(huì)調(diào)用 one() 方法
線程 B 將會(huì)調(diào)用 two() 方法
線程 C 將會(huì)調(diào)用 three() 方法
請?jiān)O(shè)計(jì)修改程序,以確保 two() 方法在 one() 方法之后被執(zhí)行,three() 方法在 two() 方法之后被執(zhí)行。
示例 1:
輸入: [1,2,3]
輸出: "onetwothree"
解釋:
有三個(gè)線程會(huì)被異步啟動(dòng)。
輸入 [1,2,3] 表示線程 A 將會(huì)調(diào)用 one() 方法,線程 B 將會(huì)調(diào)用 two() 方法,線程 C 將會(huì)調(diào)用 three() 方法。
正確的輸出是 "onetwothree"。
示例 2:
輸入: [1,3,2]
輸出: "onetwothree"
解釋:
輸入 [1,3,2] 表示線程 A 將會(huì)調(diào)用 one() 方法,線程 B 將會(huì)調(diào)用 three() 方法,線程 C 將會(huì)調(diào)用 two() 方法。
正確的輸出是 "onetwothree"。
注意:
盡管輸入中的數(shù)字似乎暗示了順序,但是我們并不保證線程在操作系統(tǒng)中的調(diào)度順序。
你看到的輸入格式主要是為了確保測試的全面性。
import java.util.concurrent.Semaphore;
class Foo {
public Semaphore seam_first_two = new Semaphore(0);
public Semaphore seam_two_second = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
seam_first_two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
seam_first_two.acquire();
printSecond.run();
seam_two_second.release();
}
public void third(Runnable printThird) throws InterruptedException {
seam_two_second.acquire();
printThird.run();
}
}