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(); } } }
結果:
有点长截取后半段吧:
49994
49996
49998
耗费时间为:7301
原文:http://www.cnblogs.com/androidsuperman/p/6642491.html