什麼是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