实现说明
活动部件是类 ServiceStartup。
for (String service : dependencies) 反复执行,循环体之外没有别的重复。资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。
使用要点
- 演示输出是带标签的(
all dependencies ready, serving traffic、startup timed out, aborting),每个操作都会留下自己的一行标注。
常见问题
运行「CountDownLatch 就绪门闩」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 all dependencies ready, serving traffic、startup timed out, aborting 标签标明各步骤。
核心语句
List<String> dependencies = List.of("config-server", "database", "cache");
代码示例
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ServiceStartup {
public static void main(String[] args) throws InterruptedException {
List<String> dependencies = List.of("config-server", "database", "cache");
// 每个依赖就绪后 countDown 一次,计数归零即全部就绪
CountDownLatch ready = new CountDownLatch(dependencies.size());
try (ExecutorService pool = Executors.newFixedThreadPool(dependencies.size())) {
for (String service : dependencies) {
pool.submit(() -> {
System.out.println(service + " warming up");
ready.countDown();
});
}
// 主线程设上限等待,超时则放弃启动而不是无限阻塞
if (ready.await(2, TimeUnit.SECONDS)) {
System.out.println("all dependencies ready, serving traffic");
} else {
System.out.println("startup timed out, aborting");
}
}
}
}