我們提供了一個類:
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"。
示例 2:
輸入: [1,3,2]
輸出: "onetwothree"
解釋:?
輸入 [1,3,2] 表示線程 A 將會調用 one() 方法,線程 B 將會調用 three() 方法,線程 C 將會調用 two() 方法。
正確的輸出是 "onetwothree"。
?
注意:
盡管輸入中的數字似乎暗示了順序,但是我們并不保證線程在操作系統中的調度順序。
你看到的輸入格式主要是為了確保測試的全面性。
first:直接執行。執行完以后將標記設為1
second:等到標記為1時執行,執行完之后把標記設為2
third:等到標記為2時執行。
Java中AtomicInteger類提供線程安全的int類型操作,具體自己查。
class Foo {private AtomicInteger done = new AtomicInteger(0);public Foo() {}public void first(Runnable printFirst) throws InterruptedException {printFirst.run();done.set(1);}public void second(Runnable printSecond) throws InterruptedException {while (done.get() != 1);printSecond.run();done.set(2);}public void third(Runnable printThird) throws InterruptedException {while (done.get() != 2);printThird.run();}
}
?