標籤:同步 進度 override 其他 pack 閉鎖 執行 main 狀態
CountDownLatch 一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。
閉鎖可以延遲線程的進度直到其到達終止狀態,閉鎖可以用來確保某些活動直到其他活動都完成才繼續執行:
- 確保某個計算在其需要的所有資源都被初始化之後才繼續執行;
- 確保某個服務在其依賴的所有其他服務都已經啟動之後才啟動;
- 等待直到某個操作所有參與者都準備就緒再繼續執行。
package com.company;import java.util.concurrent.CountDownLatch;/* * CountDownLatch :閉鎖,在完成某些運算是,只有其他所有線程的運算全部完成,當前運算才繼續執行 */public class TestCountDownLatch { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(50); LatchDemo ld = new LatchDemo(latch); long start = System.currentTimeMillis(); for (int i = 0; i < 50; i++) { new Thread(ld).start(); } try { latch.await(); } catch (InterruptedException e) { } long end = System.currentTimeMillis(); System.out.println("耗費時間為:" + (end - start)); }}class LatchDemo implements Runnable { private CountDownLatch latch; public LatchDemo(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { for (int i = 0; i < 50000; i++) { if (i % 2 == 0) { System.out.println(i); } } } finally { latch.countDown(); } }}
結果:
有點長截取後半段吧:
499944999649998耗費時間為:7301
java多線程 -- CountDownLatch 閉鎖