1.概念
倒数计时器
一种典型的场景就是火箭发射。在火箭发射前,为了保证万无一失,往往还要进行各项设备、仪器的检查。
只有等所有检查完毕后,引擎才能点火。这种场景就非常适合使用CountDownLatch。它可以使得点火线程,等待所有检查线程全部完工后,再执行。
2. 主要接口
end.countDown();
end.await();
3. 示意图
4.程序实例
package com.john.learn.high.concurent.ch03;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo implements Runnable {
private CountDownLatch countDownLatch;
public CountDownLatchDemo(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " start to check!");
Thread.sleep(new Random().nextInt(10) * 1000);
System.out.println(Thread.currentThread().getName() + " check completed!");
} catch (InterruptedException e) {
} finally {
countDownLatch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(10);
CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo(countDownLatch);
for (int i = 0; i < countDownLatch.getCount(); i++) {
new Thread(countDownLatchDemo).start();
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " Fire!");
}
}, "Wait All check completed for main Thread["+i+"]").start();
}
}
}