JUC練習代碼-力扣多線程1114題目:按續打印,解題詳解

經同事發現力扣上有多線程的題,於是花了1天多一些時間來嘗試解答,在不參考答案的情況下。終於都搞定了。

1114題目:
我們提供了一個類:

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”。

解題思路

因爲是三個線程按順序輸出一次即可。應該有很多辦法可以實現,比如利用Conditon的精準喚醒,或者信號量。
本次採取信號量,相對解答代碼簡便一些,思路也清晰一些。
初始第一個線程信號量爲1,其他兩個線程信號量爲0,第一個線程完成則給第二個線程信號量+1,以此類推即可。

class Foo {
        Semaphore one=new Semaphore(1);
        Semaphore two=new Semaphore(0);
        Semaphore three=new Semaphore(0);
        

        public Foo() {

        }

        public void first(Runnable printFirst) throws InterruptedException {
            one.acquire();
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            two.release();
            
        }

        public void second(Runnable printSecond) throws InterruptedException {
            two.acquire();
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            three.release();
        }

        public void third(Runnable printThird) throws InterruptedException {
            three.acquire();
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
            one.release();
        }
    }

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章