Java多线程 - 辅助类
# CountDownLatch 减少计数
场景:多线程处理完成后统计
缺点:初始化计数量后不能调整,不适用于未知任务数的多线程作业
点击查看
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 初始化计数数量
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
System.out.println(i);
executorService.submit(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
// 线程结束时减少
countDownLatch.countDown();
}
});
}
try {
// 阻塞等待减少至0
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成");
# CyclicBarrier 循环栅栏
todo
# Semaphore 信号灯
todo
# Phaser 移相器
CountDownLatch 的增强版,可用于不能提前确定任务总数量的情况
点击查看
@Test
void phaserTest() {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Phaser phaser = new Phaser();
for (int i = 0; i < 5; i++) {
// 注册
phaser.register();
executorService.submit(() -> {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 注销
phaser.arriveAndDeregister();
}
});
}
// 阻塞直至所有注册注销
phaser.arriveAndAwaitAdvance();
System.out.println("完成");
}
上次更新: 2022/12/31, 03:04:26