問題描述
我們提供了一個(gè)類:
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三個(gè)不同的線程將會共用一個(gè) Foo 實(shí)例。
線程 A 將會調(diào)用 one() 方法
線程 B 將會調(diào)用 two() 方法
線程 C 將會調(diào)用 three() 方法
請?jiān)O(shè)計(jì)修改程序,以確保 two() 方法在 one() 方法之后被執(zhí)行,three() 方法在 two() 方法之后被執(zhí)行。
示例 1:
輸入: [1,2,3]
輸出: "onetwothree"
解釋:
有三個(gè)線程會被異步啟動。
輸入 [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)載請注明出處。
給出的Foo類如下:
class Foo {
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
簡單問題的簡單解法:
一開始還有點(diǎn)蒙,方法說是one、two、three;然后線程A調(diào)用one,線程B調(diào)用two、線程C調(diào)用three。
接著線程可以隨意調(diào)方法了,one、two、three也變成first, second, third了,還好題目較簡單,看看注釋說明大致就清楚了。解起來也簡單,下面是一個(gè)簡單的解法, 執(zhí)行結(jié)果通過如下:
執(zhí)行用時(shí) : 10 ms, 在所有 java 提交中擊敗了97.10%的用戶
內(nèi)存消耗 : 36.2 MB , 在所有 java 提交中擊敗了100.00%的用戶
class Foo {
volatile int state = 0;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
while(state!=1){
if(state == 0){
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
state++;
}
}
}
public void second(Runnable printSecond) throws InterruptedException {
while(state != 2){
if(state == 1){
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
state++;
}
}
}
public void third(Runnable printThird) throws InterruptedException {
while(state != 3){
if(state == 2){
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
state++;
}
}
}
}
第一個(gè)方法可以不用判斷,直接打印和自增就可以,不過差別不大。