比喻
这个程序就像是5个选手在赛跑
1.5个选手都需要在跑道上准备
2.裁判需要在选手准备完毕后开枪喊开始
3.等5个选手都跑到终点 比赛结束
package concurrency;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class CountDownLatchExample {
/**
* @param executor
* @param concurrency
* @param action
* @return
* @throws InterruptedException
*/
public static long time(Executor executor, int concurrency,
final Runnable action) throws InterruptedException {
final CountDownLatch ready = new CountDownLatch(concurrency);
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch done = new CountDownLatch(concurrency);
for (int i = 0; i < concurrency; i++) {
executor.execute(new Runnable() {
public void run() {
ready.countDown(); // 告诉定时器 已准备完毕
System.out.println(Thread.currentThread().getName() + ": 准备完毕" );
try {
start.await(); // 等待其它线程都准备完毕
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown(); // 本线程任务已完成
System.out.println(Thread.currentThread().getName() + ": 跑到终点" );
}
}
});
}
ready.await(); // 祝线程等待所有工作线程都准备完毕
long startNanos = System.nanoTime();
System.out.println(Thread.currentThread().getName() + ": 裁判喊开始" );
start.countDown(); // 开始
done.await(); // 等待所有线程结束
return System.nanoTime() - startNanos;
}
public static void main(String[] args) throws Exception{
int concurrency = 5;
Executor executor = Executors.newFixedThreadPool(concurrency);
Runnable action = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ": 赛跑中" );
}
};
time(executor, concurrency, action);
}
}