//统计所有子线程就绪后开始运行直到所有子线程都运行结束后的时间
final int THREADS = 5;
CountDownLatch startGate = new CountDownLatch(1);
CountDownLatch endGate = new CountDownLatch(THREADS);
for (int i =0;i<THREADS;i++){
new Thread(() -> {
try {
//所有线程启动后阻塞在此处
startGate.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//假装有业务逻辑
for(int j =0;j<THREADS;j++){
System.out.println(j);
}
endGate.countDown();
}).start();
}
long startTime = System.currentTimeMillis();
//启动门为0,线程开始运行await后的代码
startGate.countDown();
try {
//主线程阻塞,等待所有子线程结束才能运行
endGate.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
CountDownLatch,启动门结束门示例
最新推荐文章于 2022-03-22 18:48:07 发布