在 Java 中,**Executor(执行器)**本身只是一个接口,真正需要“关闭”的是它的实现类,最常用的是 ThreadPoolExecutor 以及通过 Executors 工厂方法创建的线程池。
下面按常见场景说明如何关闭。
ExecutorService 是 Executor 的子接口,提供了关闭方法。
shutdown()executorService.shutdown();
特点:
适用场景:
shutdownNow()List<Runnable> unfinished = executorService.shutdownNow();
特点:
Thread.interrupt())适用场景:
awaitTermination(通常配合 shutdown 使用)executorService.shutdown();
try {
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
流程说明:
shutdown()shutdownNow()ExecutorService pool = Executors.newFixedThreadPool(10);
// 使用完后
pool.shutdown();
⚠️ 注意:
Executors.newCachedThreadPool() 也可能一直存活如果你用的是 Spring 的 ThreadPoolTaskExecutor:
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);
executor.initialize();
return executor;
}
Spring 容器关闭时会自动调用 shutdown()。
❌ 只提交任务不关闭线程池
❌ 用 shutdownNow() 后认为任务一定停止
❌ 在 finally 外关闭线程池
✅ 推荐写法:
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(() -> {});
} finally {
executor.shutdown();
}
| 方法 | 是否接受新任务 | 是否执行已有任务 | 是否阻塞 |
|---|---|---|---|
| shutdown | ❌ | ✅ | ❌ |
| shutdownNow | �️ | ❌(尝试中断) | ❌ |
| awaitTermination | - | - | ✅ |
如果你有 具体线程池类型(如 ForkJoinPool / ScheduledExecutorService) 或使用场景,我可以给更针对性的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。