LeetCode 1114題:按序打印,多線程執行順序

LeetCode1114題。該題主要解決多線程執行順序問題。

題目描述

我們提供了一個類:

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

注意:
儘管輸入中的數字似乎暗示了順序,但是我們並不保證線程在操作系統中的調度順序。
你看到的輸入格式主要是爲了確保測試的全面性

解法

解題思路有幾個要點:

  1. 無論採用何種方式,開始時必須執行first線程
  2. 當first線程執行完且只有first線程執行完,要設置條件滿足second執行,而first和third線程都不能執行
  3. 同理second線程執行完,設置條件滿足third執行,而first和second線程都不能執行

下面列出三種方法,個人推薦Semaphore方法,直觀易懂。

Semaphore(信號量)

Semaphore與下一個CountDownLatch相似,不同的地方在於Semaphore的值被獲取到後是可以釋放的,並不像CountDownLatch那樣一直減到底

獲得Semaphore的線程處理完它的邏輯之後,你就可以調用它的Release()函數將它的計數器重新加1,這樣其它被阻塞的線程就可以得到調用了

public class Foo03 {
    //聲明兩個 Semaphore變量
    private Semaphore spa,spb;
    public Foo03() {
        //初始化Semaphore爲0的原因:如果這個Semaphore爲零,如果另一線程調用(acquire)這個Semaphore就會產生阻塞,便可以控制second和third線程的執行
        spa = new Semaphore(0);
        spb = new Semaphore(0);
    }
    public void first(Runnable printFirst) throws InterruptedException {
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            //只有等first線程釋放Semaphore後使Semaphore值爲1,另外一個線程纔可以調用(acquire)
            spa.release();
    }
    public void second(Runnable printSecond) throws InterruptedException {
            //只有spa爲1才能執行acquire,如果爲0就會產生阻塞
            spa.acquire();
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            spb.release();
    }
    public void third(Runnable printThird) throws InterruptedException {
            //只有spb爲1才能通過,如果爲0就會阻塞
            spb.acquire();
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
    }
}

CountDownLatch

該方法與Semaphore類似,直接借用線程工具類、設置吞吐量,控制後置進程的觸發時機。

public class Foo {
    //聲明兩個 CountDownLatch變量
    private CountDownLatch countDownLatch01, countDownLatch02;

    public Foo() {
        //初始化每個CountDownLatch的值爲1,表示有一個線程執行完後,執行等待的線程
        countDownLatch01 = new CountDownLatch(1);
        countDownLatch02 = new CountDownLatch(1);
    }
    public void first(Runnable printFirst) throws InterruptedException {
            //當前只有first線程沒有任何的阻礙,其餘兩個線程都處於等待階段
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            //直到CountDownLatch01裏面計數爲0才執行因調用該countDownCatch01.await()而等待的線程
            countDownLatch01.countDown();
    }
    public void second(Runnable printSecond) throws InterruptedException {
            //只有countDownLatch01爲0才能通過,否則會一直阻塞
            countDownLatch01.await();
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            //直到CountDownLatch02裏面計數爲0才執行因調用該countDownCatch02.await()而等待的線程
            countDownLatch02.countDown();
    }
    public void third(Runnable printThird) throws InterruptedException {
            //只有countDownLatch02爲0才能通過,否則會一直阻塞
            countDownLatch02.await();
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
    }
}

Synchronized鎖和控制變量

該方法實現代碼較多、邏輯複雜。實際上Semaphore底層採用近似機制。

public class Foo {
    //控制變量
    private int flag = 0;
    //定義Object對象爲鎖
    private Object lock = new Object();
    public Foo() {
    }
    public void first(Runnable printFirst) throws InterruptedException {
        synchronized (lock){
            //如果flag不爲0則讓first線程等待,while循環控制first線程如果不滿住條件就一直在while代碼塊中,防止出現中途跳入,執行下面的代碼,其餘線程while循環同理
            while( flag != 0){
                lock.wait();
            }
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            //定義成員變量爲 1
            flag = 1;
            //喚醒其餘所有的線程
            lock.notifyAll();
        }
    }
    public void second(Runnable printSecond) throws InterruptedException {
        synchronized (lock){
            //如果成員變量不爲1則讓二號等待
            while (flag != 1){
                lock.wait();
            }
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            //如果成員變量爲 1 ,則代表first線程剛執行完,所以執行second,並且改變成員變量爲 2
            flag = 2;
            //喚醒其餘所有的線程
            lock.notifyAll();
        }
    }
    public void third(Runnable printThird) throws InterruptedException {
        synchronized (lock){
            //如果flag不等於2 則一直處於等待的狀態
            while (flag != 2){
                lock.wait();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            //如果成員變量爲 2 ,則代表second線程剛執行完,所以執行third,並且改變成員變量爲 0
            printThird.run();
            flag = 0;
            lock.notifyAll();
        }
    }
}

以上。感謝您的閱讀。

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