实现说明
全部逻辑都在类 ExecutorAutoClose中。
文件的主干是一个循环——for (int i = 1; i <= 3; i++)。不需要 finally——try 头部声明的资源按相反顺序自行关闭。
使用要点
- 跑完文件,输出里会留下标记——
submitted; close() will wait for all three、close waited:。
常见问题
运行「ExecutorService 的 AutoCloseable 优雅关闭」会打印什么?
运行文件本身,submitted; close() will wait for all three、close waited: 这些前缀各对应一段演示逻辑。
核心语句
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (int i = 1; i <= 3; i++) {
int job = i;
executor.submit(() -> {
Thread.sleep(50);
return "job " + job + " done";
});
}
System.out.println("submitted; close() will wait for all three");
}
代码示例
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorAutoClose {
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
// JDK 19+:ExecutorService 实现 AutoCloseable
// 离开 try 块时 close() 先 shutdown 再阻塞,等所有已提交任务跑完
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (int i = 1; i <= 3; i++) {
int job = i;
executor.submit(() -> {
Thread.sleep(50);
return "job " + job + " done";
});
}
System.out.println("submitted; close() will wait for all three");
}
Duration waited = Duration.between(start, Instant.now());
System.out.println("close waited: " + waited.toMillis() + "ms");
}
}