CountDownLatch 用于阻塞一条或多条线程,直至其它线程把工作完成。
构那建器:
CountDownLatch(int count);count为计数器
方法:await()
调用await方法的线程在计数器=0前一直阻塞,除非线程被中断
。
将计数器count-1,如果计数到达零,则唤醒因为调用await方法而阻塞的所有的线程。
调用完countDown()方法后线程会继续执行。
一般用于一个线程或多个线程 ,等待其它线程完成count个工作,才继续执行。
示例:
public class TestCountDownLatch implements Runnable{
CountDownLatch countDownLatch = null;
String threadName = null;
public TestCountDownLatch(String threadName,CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
this.threadName = threadName;
}
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
public void run() {
// TODO Auto-generated method stub
try{
System.out.println(sdf.format(new Date())+": "+this.threadName +" start work");
Thread.sleep(5000);
System.out.println(sdf.format(new Date())+": "+this.threadName +" finish work");
countDownLatch.countDown();//每次调用countDown 计算器-1 如果不调用该方法,countDownLatch.await()会一直阻塞
System.out.println(sdf.format(new Date())+": "+this.threadName +" to exit");//线程退出
}catch(Exception e){
e.printStackTrace();
}finally{
countDownLatch.countDown();//计数减一
}
}
public static void main(String args []){
CountDownLatch countDownLatch = new CountDownLatch(5);//5个计数,每次调用countDown -1
ExecutorService es=Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
es.execute(new TestCountDownLatch("Thread_"+i,countDownLatch));
}
es.shutdown();
try{
System.out.println("main thread blocking");
countDownLatch.await();//等待5次countDown方法调用,即计数器为0时, await方法阻塞才结束,执行后续线程, CountDownLatch类计数器清0后不能再使用,重复使用可以使用CyclicBarrier
System.out.println("main thread wake up");
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(sdf.format(new Date())+": all thread run finish");
}
}
执行结果:
2013-11-14 09:31:31: Thread_0 start work
2013-11-14 09:31:31: Thread_1 start work
main thread blocking
2013-11-14 09:31:31: Thread_3 start work
2013-11-14 09:31:31: Thread_2 start work
2013-11-14 09:31:31: Thread_4 start work
2013-11-14 09:31:36: Thread_1 finish work
2013-11-14 09:31:36: Thread_1 to exit
2013-11-14 09:31:36: Thread_0 finish work
2013-11-14 09:31:36: Thread_0 to exit
2013-11-14 09:31:36: Thread_2 finish work
2013-11-14 09:31:36: Thread_3 finish work
main thread wake up
2013-11-14 09:31:36: Thread_2 to exit
2013-11-14 09:31:36: Thread_4 finish work
2013-11-14 09:31:36: Thread_3 to exit
2013-11-14 09:31:36: Thread_4 to exit
2013-11-14 09:31:37: all thread run finish