java併發編程學習之CountDownLatch

做用

等待其餘線程執行完後,在執行某個線程。相似以前的join,可是比join更強大。join能夠多個線程插隊到A線程,A線程等多個線程結束後才執行(相似後面的CyclicBarrier),而CountDownLatch能夠等待多個線程執行完才執行,靈活性比join更大。segmentfault

主要方法

  1. countDown,計數器減1。這個方法能夠一個線程執行一次,也能夠一個線程執行屢次。
  2. await,堵塞,等計數減爲0的時候,才繼續執行。

示例

public class CountDownLatchDemo {
    static CountDownLatch countDownLatch = new CountDownLatch(2);

    static class Thread1 implements Runnable {
        @Override
        public void run() {
            countDownLatch.countDown();
            System.out.println(Thread.currentThread().getName() + ":" + 1);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":" + 2);
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) {
        Thread thread =new Thread(new Thread1(),"thread");
        thread.start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ":" + 3);
    }
}

執行結果以下:
clipboard.png
雖然線程thread休眠了2秒,可是main依然等到線程thread輸出2後,才輸出3。ide

相關文章
相關標籤/搜索