本文翻译自http://tutorials.jenkov.com/java-util-concurrent/countdownlatch.html,人工翻译,仅供学习交流。
CountDownLatch
java.util.concurrent.CountDownLatch是一个允许一个或多个线程等待一组给定的操作完成后的并发结构。
闭锁初始化给定一个计数,这个值会通过调用countDown()方法增加。一直等待到为0的线程可以先调用await()方法进行等待。调用await()方法会阻塞线程直到计数为0。
下面是一个简单的例子,Decrementer在CountDownLatch上调用了countDown() 3次之后,等待中的Waiter线程从await()调用中释放。
CountDownLatch latch = new CountDownLatch(3);
Waiter waiter = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter) .start();
new Thread(decrementer).start();
Thread.sleep(4000);
public class Waiter implements Runnable{
CountDownLatch latch = null;
public Waiter(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Waiter Released");
}
}
public class Decrementer implements Runnable {
CountDownLatch latch = null;
public Decrementer(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}