类型 | 定义 | 例子 | 超时例子 |
---|
CountDownLatch | 一个(或多个)线程等待其他线程(彼此独立) 执行完成 | 每个人(其他线程 )下班打卡(countDown)后,各回各家(彼此独立 );等人都走光后,保卫大爷(等待线程 )才关门(await ) | 保卫大爷(等待线程 )到点就关门(await),即使还有人没下班 |
CyclicBarrier | 多个线程互相等待 ,直到所有线程到达同一个同步点。并且可以重复使用(节能环保 ) | 开会时,一般需要参会人(多个线程 )都到会议室(await同步点 )后,才能开会 | 参会人(多个线程 )等待(await)一定时间后,即使有人缺席,还是要开会 |
CountDownLatch示例
代码
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(3);
ExecutorService threadPool = Executors.newFixedThreadPool(10);
int threadCount = 3;
for (int i = 0; i < threadCount; i++) {
final int threadNum = i;
Thread.sleep(1000);
threadPool.execute(() -> {
try {
System.out.printf("开始上班::threadNum=%d time=%s %n", threadNum, getTime());
Thread.sleep(8);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("打卡下班::threadNum=%d time=%s %n", threadNum, getTime());
countDownLatch.countDown();
System.out.printf("打卡完毕,各回各家::threadNum=%d time=%s %n", threadNum, getTime());
System.out.println("**********\n");
});
}
System.out.println("保卫大爷等待关门...");
countDownLatch.await();
threadPool.shutdown();
System.out.println("保卫大爷关门回家!");
}
private static String getTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss S");
return simpleDateFormat.format(new Date());
}
结果

CyclicBarrier示例
代码
public static void main(String[] args) throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
ExecutorService threadPool = Executors.newFixedThreadPool(10);
int threadCount = 3;
for (int i = 0; i < threadCount; i++) {
final int threadNum = i;
Thread.sleep(1000);
threadPool.execute(() -> {
try {
System.out.printf("到达会议室::threadNum=%d time=%s %n", threadNum, getTime());
System.out.printf("已等待人数::%d 人%n", cyclicBarrier.getNumberWaiting());
System.out.println("**********\n");
cyclicBarrier.await();
System.out.printf("开始开会::threadNum=%d time=%s %n", threadNum, getTime());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
}
threadPool.shutdown();
}
private static String getTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss S");
return simpleDateFormat.format(new Date());
}
结果
