作用:用于一个或多个线程等待其它(一个或多个线程)完成相关操作.像日常生活的门锁一样,比如门装了三把锁,只有当三个把锁都打开时,门才能被打开.
方法:
CountDownLatch(int count)初始化闭锁,指定闩数量.
await();等待通过锁,只有所有的闩都释放后,才能通过锁,阻塞当前线程.
countDown();释放一个闩;
//同 await(),这里指定一个等待超时时间,当到达指定的超时时间后,闩的数量没有减少到0,则返回 false,这里注意当前线程会阻塞指定的超时时间;
//若在指定超时时间内,闩的数量减少到0,会立即返回 true.
boolean await(long timeout, TimeUnit unit);
long getCount();//获取闩的数量,主要用于调试
实现原理:
请参考抽象同步队列(AbstractQueuedSynchronizer)
例子:
1 public class CountDownLatchDemo { 2 3 private static CountDownLatch countDownLatch=new CountDownLatch(100); 4 5 private static int index=0; 6 public static void main(String[] args) { 7 try { 8 for(int i=0;i<5;++i){ 9 new Thread(){ 10 @Override 11 public void run() { 12 try { 13 System.out.println("the thread "+Thread.currentThread().getId()+" pre entry the countdownlatch"); 14 countDownLatch.await(); 15 System.out.println("the thread "+Thread.currentThread().getId()+" pass the countdonwlatch!"); 16 }catch (Throwable throwable){ 17 throwable.printStackTrace(); 18 } 19 } 20 }.start(); 21 } 22 while (index++<100) { 23 new Thread() { 24 @Override 25 public void run() { 26 try { 27 Thread.sleep(100); 28 } catch (Throwable throwable) { 29 throwable.printStackTrace(); 30 } 31 32 System.out.println("countdown of thread " + Thread.currentThread().getId()); 33 countDownLatch.countDown(); 34 } 35 }.start(); 36 } 37 System.in.read(); 38 }catch (Throwable throwable){ 39 throwable.printStackTrace(); 40 } 41 42 43 } 44 }