1. 程式人生 > 實用技巧 >多執行緒併發工具類01-CountDownLatch 執行緒工具類

多執行緒併發工具類01-CountDownLatch 執行緒工具類

     CountDownLatch:概念是,允許一個或多個執行緒等待其他執行緒完成操作;

     線上程基礎知識中,學習過執行緒的join方法,當前執行緒阻塞等待join執行緒執行完畢才能執行;

     測試程式碼如下:

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread("Thread001") {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"操作1");
        }
    };
    Thread t2 = new Thread("Thread002") {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+"操作2");
                t1.join();
                System.out.println("========這是第二部分內容===========");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t1.start();
    t2.start();
    t2.join();
    System.out.println("執行緒執行完畢");
}

上面程式碼的流程是:
1. t1和t2執行緒開啟之後,t2.join(),主執行緒阻塞;

     2.執行緒t2中,執行緒t1.join(),執行緒t2成阻塞狀態;

     3.等待t1結束玩成,t2才能繼續執行

     4.t2執行緒執行完畢,最後主執行緒執行

  CountDownLatch提供了await()方法,和countDown()方法來進行執行緒的阻塞;await()方法阻塞當前執行緒,直到countDown()的個數和CountDownLatch的初始化值相同時;

public static void main(String[] args) {
        try {
            CountDownLatch cdt = new CountDownLatch(2);
            Thread t1 = new Thread("Thread001") {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"執行了!");
                    cdt.countDown();
                }
            };
            Thread t2 = new Thread("Thread002") {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "執行了!");
                    cdt.countDown();
                }
            };
            t1.start();
            t2.start();
            cdt.await();
            System.out.println("主執行緒執行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }
    }