← 中文资源

简体中文版本

CyclicBarrier 分阶段会合

CyclicBarrier 与 CountDownLatch 不同:栅栏可重复使用。每轮工作结束后所有 worker 在 await 处等齐,最后到达者触发栅栏动作,然后一起进入下一轮。

阅读英文原文

实现说明

逻辑集中在类 PhasedCrawler里。 重复被限制在 for (String shard : shards) 里——其余代码按顺序各跑一遍。资源写在 try 头部,关闭由编译器生成、异常安全。

使用要点

  • 跑完文件,输出里会留下标记——-- phase done, all workers synced。

常见问题

运行「CyclicBarrier 分阶段会合」会打印什么?

运行文件本身,-- phase done, all workers synced 这些前缀各对应一段演示逻辑。

核心语句

Thread.currentThread().interrupt();

代码示例

import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PhasedCrawler {

    public static void main(String[] args) throws InterruptedException {
        List<String> shards = List.of("shard-a", "shard-b", "shard-c");
        // 与 CountDownLatch 不同:栅栏可重复使用,每轮都重新集合
        CyclicBarrier barrier = new CyclicBarrier(shards.size(),
                () -> System.out.println("-- phase done, all workers synced"));

        try (ExecutorService pool = Executors.newFixedThreadPool(shards.size())) {
            for (String shard : shards) {
                pool.submit(() -> {
                    try {
                        for (int phase = 1; phase <= 2; phase++) {
                            System.out.println(shard + " working phase " + phase);
                            // 等所有 worker 到齐再进下一轮;超时会打破栅栏
                            barrier.await(2, TimeUnit.SECONDS);
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } catch (BrokenBarrierException | TimeoutException e) {
                        System.out.println(shard + " gave up: " + e);
                    }
                });
            }
        }
    }
}