新增:new CyclicBarrier() 循环栅栏,同步辅助类

This commit is contained in:
duandazhi 2022-08-04 16:29:48 +08:00
parent e3c6e4e2c7
commit b9f2a91457

View File

@ -296,6 +296,8 @@ public class ThreadUtil {
* }
* </pre>
*
* 该示例也可以用{@link Phaser} 移相器 进行实现
*
* @param taskCount 任务数量
* @return CountDownLatch
*/
@ -303,6 +305,46 @@ public class ThreadUtil {
return new CountDownLatch(taskCount);
}
/**
* 新建一个CycleBarrier 循环栅栏一个同步辅助类
*
* 示例7个同学集齐7个龙珠7个同学一起召唤神龙前后集齐了2次
* <pre>{@code
* AtomicInteger times = new AtomicInteger();
* CyclicBarrier barrier = new CyclicBarrier(7, ()->{
* System.out.println("");
* System.out.println("");
* System.out.println("【循环栅栏业务处理】7个子线程 都收集了一颗龙珠,七颗龙珠已经收集齐全,开始召唤神龙。" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
* times.getAndIncrement();
* }); // 现在设置的栅栏的数量为2
* for (int x = 0; x < 7; x++) { // 创建7个线程, 当然也可以使用线程池替换
* new Thread(() -> {
* while (times.get() < 2) {
* try {
* System.out.printf("【Barrier - 收集龙珠】当前的线程名称:%s%n", Thread.currentThread().getName());
* int time = ThreadLocalRandom.current().nextInt(1, 10); // 等待一段时间模拟线程的执行时间
* TimeUnit.SECONDS.sleep(time); // 模拟业务延迟收集龙珠的时间
* barrier.await(); // 等待凑够了7个等待的线程
* System.err.printf("〖Barrier - 举起龙珠召唤神龙〗当前的线程名称:%s\t%s%n", Thread.currentThread().getName(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
* if (barrier.getParties() >= 7) {
* barrier.reset(); // 重置栅栏等待下一次的召唤
* }
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
* }, "线程 - " + x).start();
* }
* }</pre>
*
* 该示例也可以用{@link Phaser} 移相器 进行实现
* @param taskCount 任务数量
* @return 循环栅栏
*/
public static CyclicBarrier newCyclicBarrier(final int taskCount) {
return new CyclicBarrier(taskCount);
}
/**
* 新建一个Phaser一个同步辅助类jdk1.7提供可以完全替代CountDownLatch
* @since 6.0.1