为什么执行器服务接口不实现自动关闭?
2022-09-01 06:47:15
未能调用线程执行程序将导致应用程序永不终止。shutdown()
关闭执行器服务的最佳实践是:
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
// add tasks to thread executor
…
} finally {
if (service != null) service.shutdown();
}
既然Java知道试用资源的概念,如果我们能做到这一点,那不是很好吗?
try (service = Executors.newSingleThreadExecutor())
{
// add tasks to thread executor
…
}