在 Java 中,和 Go 的 sync.WaitGroup 功能最接近的同步工具是:


✅ java.util.concurrent.CountDownLatch

🧩 类似用途:

用于等待一组并发任务完成,就像 WaitGroup.Wait() 等待所有 goroutine 结束一样。


✅ 基本用法示例:

import java.util.concurrent.CountDownLatch;

public class WaitGroupExample {
    public static void main(String[] args) throws InterruptedException {
        int workerCount = 3;
        CountDownLatch latch = new CountDownLatch(workerCount);

        for (int i = 0; i < workerCount; i++) {
            int id = i + 1;
            new Thread(() -> {
                System.out.println("Worker " + id + " started.");
                try {
                    Thread.sleep(1000); // 模拟任务
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                System.out.println("Worker " + id + " done.");
                latch.countDown(); // 相当于 WaitGroup 的 Done()
            }).start();
        }

        latch.await(); // 相当于 WaitGroup 的 Wait()
        System.out.println("All workers completed.");
    }
}

📌 方法对比表

功能 Go sync.WaitGroup Java CountDownLatch
初始化 无需初始值,动态 Add(n) 创建时指定计数:new CountDownLatch(n)
增加计数 Add(n) ❌ 不支持动态增加
减少计数 Done()(等价于 Add(-1)) countDown()
等待所有任务完成 Wait() await()

⚠️ 注意:


🆚 总结对照:Go vs Java

场景 Go Java
等待一组并发任务完成 sync.WaitGroup CountDownLatch
多阶段同步(多轮 barrier) 手动实现或用 channel 控制 CyclicBarrier / Phaser
超时等待 select + time.After await(timeout, TimeUnit)
手动控制并发数量 channel 限流 Semaphore

📎 参考文章