java.util.concurrent.CountDownLatch是一个并发结构,它允许一个或多个线程等待一组给定的操作完成。CountDownLatch用给定的计数进行初始化。该计数通过调用countDown()方法递减。等待此计数达到零的线程可以调用await()方法之一。调用await()会阻塞该线程,直到计数达到零。
下面是一个简单的例子。在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)
网友评论