leetcode多線程之按序打印

本文主要記錄一下leetcode多線程之按序打印網絡

題目

咱們提供了一個類:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

三個不一樣的線程將會共用一個 Foo 實例。

    線程 A 將會調用 first() 方法
    線程 B 將會調用 second() 方法
    線程 C 將會調用 third() 方法

請設計修改程序,以確保 second() 方法在 first() 方法以後被執行,third() 方法在 second() 方法以後被執行。

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/print-in-order
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。

題解

使用juc包的CountDownLatch多線程

class Foo {

    CountDownLatch second = new CountDownLatch(1);
    CountDownLatch third = new CountDownLatch(1);

    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        second.countDown();
        
    }

    public void second(Runnable printSecond) throws InterruptedException {
        second.await();
        printSecond.run();
        third.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        third.await();
        printThird.run();
    }
}

小結

這裏是固定要按first先執行,然後second,再third方法,這裏使用了CountDownLatch,比起object的wait notify之類用起來簡單一點線程

doc

相關文章
相關標籤/搜索