多線程 按序打印

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();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容