【詳解】Java多線程之Count down設計模式

分析

  • Count-Down設計模式其實也叫做Latch(閥門)設計模式。
  • 當若干個線程併發執行完某個特定的任務,然後等到所有的子任務都執行結束之後再統一彙總。

JDK包中的實現

public class JDKCountDown {
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {

        final CountDownLatch latch = new CountDownLatch(5);

        System.out.println("準備多線程處理任務....");
        //the firth phase.
        IntStream.rangeClosed(1,5).forEach(i->
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " is working....");
                try {
                    Thread.sleep(RANDOM.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            },String.valueOf(i)).start()
        );

        latch.await();

        //the second phase.
        System.out.println("多線程任務全部結束,進行第二階段.....");
    }
}

模擬CountDown

public class CountDown {
    private final int total;

    private int counter  ;

    public CountDown(int total) {
        this.total = total;
        counter = 0;
    }

    public synchronized void down(){
        this.counter++;
        this.notifyAll();
    }

    public synchronized void await() throws InterruptedException {
        while (counter!=total){
            this.wait();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章