← 中文资源

简体中文版本

CountDownLatch 双门控起跑与汇合

用一对 CountDownLatch 协调并发任务:计数为 1 的 startGate 让全部工作线程同时起跑,计数为 N 的 doneGate 用 getCount 和 await 等待全员收工。

阅读英文原文

实现说明

活动部件是类 DualGateRunner。 循环只出现在 for (int i = 1; i <= workers; i++),它的每次迭代处理一个元素。

使用要点

  • 运行之前不需要往项目里加任何东西。
  • 演示输出是带标签的(worker-、pending before start:、pending after await:),每个操作都会留下自己的一行标注。

常见问题

运行「CountDownLatch 双门控起跑与汇合」会打印什么?

整个文件跑完,输出行以 worker-、pending before start:、pending after await: 这类前缀开头。

核心语句

ExecutorService pool = Executors.newFixedThreadPool(workers);
Thread.currentThread().interrupt();

代码示例

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DualGateRunner {

    public static void main(String[] args) throws InterruptedException {
        int workers = 3;
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch doneGate = new CountDownLatch(workers);

        ExecutorService pool = Executors.newFixedThreadPool(workers);
        for (int i = 1; i <= workers; i++) {
            int id = i;
            pool.submit(() -> {
                try {
                    startGate.await(); // all workers pause until the gun fires
                    System.out.println("worker-" + id + " ran");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    doneGate.countDown(); // always signal completion
                }
            });
        }

        System.out.println("pending before start: " + doneGate.getCount());
        startGate.countDown(); // release every waiting worker at once
        doneGate.await(3, TimeUnit.SECONDS);
        System.out.println("pending after await: " + doneGate.getCount());

        pool.shutdown();
        pool.awaitTermination(2, TimeUnit.SECONDS);
    }
}