diff --git a/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java b/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java index 45bdc0967..c244ff5b6 100644 --- a/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/thread/ThreadUtil.java @@ -296,6 +296,8 @@ public class ThreadUtil { * } * * + * 该示例,也可以用:{@link Phaser} 移相器 进行实现 + * * @param taskCount 任务数量 * @return CountDownLatch */ @@ -303,6 +305,46 @@ public class ThreadUtil { return new CountDownLatch(taskCount); } + /** + * 新建一个CycleBarrier 循环栅栏,一个同步辅助类 + * + * 示例:7个同学,集齐7个龙珠,7个同学一起召唤神龙;前后集齐了2次 + *
{@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();
+ * }
+ * }
+ *
+ * 该示例,也可以用:{@link Phaser} 移相器 进行实现
+ * @param taskCount 任务数量
+ * @return 循环栅栏
+ */
+ public static CyclicBarrier newCyclicBarrier(final int taskCount) {
+ return new CyclicBarrier(taskCount);
+ }
+
/**
* 新建一个Phaser,一个同步辅助类,jdk1.7提供,可以完全替代CountDownLatch;
* @since 6.0.1