什么是CountDownLatch
CountDownLatch是一种同步类,它运行一个线程在执行前等待一个或多个线程,这经常用于服务器端开发。通常当主线程调用await()方法后将会等待直到计数器到达0或者被其它线程中断。其它线程通过调用countDown()方法将会在完成任务后将计数器减1。计数器为0是主线程将开始运行。
CountDownLatch 例子
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo{
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start(); //separate thread will initialize CacheService
alertService.start(); //another thread for AlertService initialization
validationService.start();
try{
latch.await();
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(timeToStart);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println( name + " is Up");
latch.countDown(); //reduce count of CountDownLatch by 1
}
}<strong>
</strong>
output:
AlertService is Up
CacheService is Up
ValidationService is Up
All services are up, Application is starting now
知识点:
1.CountDownLatch 一旦计数器减到0将不能被重用,这是和CyclicBarrier主要的区别
2.主线程调用await()方法等待,其它线程调用countDown()方法来通知主线程已经完成
参考:
http://javarevisited.blogspot.hk/2012/07/countdownlatch-example-in-java.html