目录
- 在 Java 中,和 Go 的 sync.WaitGroup 功能最接近的同步工具是:
- ✅ java.util.concurrent.CountDownLatch
- 🧩 类似用途:
- 用于等待一组并发任务完成,就像 WaitGroup.Wait() 等待所有 goroutine 结束一样。
- ✅ 基本用法示例:
- 📌 方法对比表
- ⚠️ 注意:
- 🆚 总结对照:Go vs Java
- 📎 参考文章
在 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.");
}
}
📌 方法对比表#
⚠️ 注意:#
CountDownLatch 是一次性使用的:计数归零后就不能再重用;
- 若需要可重复使用的同步工具,可用:
- ✅
CyclicBarrier: 等待 N 个线程到达再继续
- ✅
Phaser: 更灵活的多阶段任务同步(可动态注册线程)
🆚 总结对照:Go vs Java#
📎 参考文章#