CountDownLatch是一个同步辅助类,在完成一组正在其余线程中执行的操做以前,容许一个或者多个线程一直等待。ide
闭锁能够延迟线程的进度直到其到达终止状态,能够确保某些活动知道其余活动都完成才继续执行this
注意:在run方法中必须将调用countdown方法 计数减1 而且在new CountDownLatch时建立的个数要和for循环中的线程个数相等,而且调用latch.await()方法进行等到全部的thread执行完毕。spa
应用场景:线程
例如 超市中多个线程计算每一个种类的商品的信息 ,使用countdownlatch等到各个种类的信息计算完以后,统计总信息。code
/** * countdownlatch 闭锁 在完成某些运算时,只有其余全部thread得运算所有完成 当前运算才能继续执行 */ public class TestCountDownLatch { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(5); CDLDemo ld= new CDLDemo(latch); long start =System.currentTimeMillis(); for(int i=0;i<5;i++){ new Thread(ld).start(); } try{ latch.await(); }catch (InterruptedException e){ } long end = System.currentTimeMillis(); System.out.println("use time:================"+(end-start)); } } class CDLDemo implements Runnable { private CountDownLatch latch; CDLDemo(CountDownLatch latch) { this.latch = latch; } @Override public void run() { synchronized (this){ try{ for(int i=0;i<500;i++){ if(i%2==0) System.out.println(i); } }finally { latch.countDown(); } } } }