CountDownLatch
java.util.concurrent.CountDownLatch
是一个并发构造允许一个或者多个线程等待给定的一组操作完成。
CountDownLatch
初始化时设置了一个给定的值,当调用
countDown()
方法时这个值会递减,
当这个只为0的时候将唤醒众多调用 await()
方法线程中的一个线程,调用await()
方法的线程将一直阻塞直到count为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();
}
}
}
参考翻译:http://tutorials.jenkov.com/java-util-concurrent/countdownlatch.html