CountDownLatch允许一个或多个线程等待其它线程完成操作。
CountDownLatch的构造函数接收一个int类型的参数作为计数器,想等待N个任务线程完成就传N。当countDown方法被调用N就会减一,await方法会阻塞当前线程直到N变为0。
主要的功能就是通过await()方法来阻塞线程,然后等待计数器减少到0了,再唤起那些等待的线程继续;即你想要某些线程等待另一些线程执行完再执行,就可以使用CountDownLatch。
先来看看用法:
//三个线程阻塞直到主线程执行完
public void test1() {
final CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " wait;");
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " start");
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
//主线程阻塞等待直到三个线程都执行完
public void test2() {
final CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " start");
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All end");
}
在举一个创建Zookeeper实例的例子
protected ZooKeeper zooKeeper;
// 阻塞直到连接成功
private CountDownLatch latch = new CountDownLatch(1);
/**
* 连接ZK服务器
* @param address 地址
*/
protected void connectServer(String address) {
try {
this.zooKeeper = new ZooKeeper(address, ZK_SESSION_TIMEOUT, event -> {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
if (Watcher.Event.EventType.None == event.getType()) {
latch.countDown();
log.info("ZK连接成功");
}
}
});
log.info("开始连接ZK服务器");
latch.await();
} catch (IOException | InterruptedException e) {
log.error("", e);
}
}
源码
下面出现的很多方法都在之前AQS的文章里分析过了,这里就不重复了。
构造函数:同步状态state的值在CountDownLatch构造函数中赋值(AQS为同步状态提供了getState,setState方法,state是volatile修饰)。
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}