題目
我們提供了一個類:
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三個不同的線程將會共用一個 Foo 實例妻熊。
線程 A 將會調(diào)用 one() 方法
線程 B 將會調(diào)用 two() 方法
線程 C 將會調(diào)用 three() 方法
請設(shè)計修改程序决侈,以確保 two() 方法在 one() 方法之后被執(zhí)行区匠,three() 方法在 two() 方法之后被執(zhí)行九巡。
示例 1:
輸入: [1,2,3]
輸出: "onetwothree"
解釋:
有三個線程會被異步啟動哺徊。
輸入 [1,2,3] 表示線程 A 將會調(diào)用 one() 方法室琢,線程 B 將會調(diào)用 two() 方法,線程 C 將會調(diào)用 three() 方法落追。
正確的輸出是 "onetwothree"盈滴。
示例 2:
輸入: [1,3,2]
輸出: "onetwothree"
解釋:
輸入 [1,3,2] 表示線程 A 將會調(diào)用 one() 方法,線程 B 將會調(diào)用 three() 方法轿钠,線程 C 將會調(diào)用 two() 方法巢钓。
正確的輸出是 "onetwothree"。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/print-in-order
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有谣膳。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán)竿报,非商業(yè)轉(zhuǎn)載請注明出處。
解法 CountDownLatch
- 代碼實現(xiàn)
import java.util.concurrent.CountDownLatch;
class Foo {
private static final int threadCount = 1;
private CountDownLatch secondLatch = new CountDownLatch(threadCount);
private CountDownLatch thirdLatch = new CountDownLatch(threadCount);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
secondLatch.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
secondLatch.await();
printSecond.run();
thirdLatch.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
thirdLatch.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
- [CountDownLatch 解析](http://www.reibang.com/writer#/notebooks/40148237/notes/54972805)