未能在线程执行器上调用 shutdown()
将导致应用程序永不终止。
关闭 ExecutorService 的最佳做法是:
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
// add tasks to thread executor
…
} finally {
if (service != null) service.shutdown();
}
既然 Java 知道 try-with-resources 的概念,如果我们能做到这一点不是很好吗?
try (service = Executors.newSingleThreadExecutor())
{
// add tasks to thread executor
…
}
最佳答案
那个 ExecutorService实际上有两个与关闭相关的方法;基于一个简单的事实,即两种关闭服务的方式都是有意义的。
因此:那么您将如何自动关闭服务?以一致的方式适用于所有人?!
所以,在我看来,合理的解释是:您不能将 ExecutorService 设为 AutoClosable,因为该服务没有单一的“关闭”类操作;但是两个!
如果你认为你可以很好地利用这种自动关闭服务,那么使用“委托(delegate)”编写你自己的实现将是 5 分钟的事情!或者可能需要 10 分钟,因为您将创建一个调用 shutdown()
作为关闭操作的版本;还有一个是 shutdownNow()
代替。
关于java - 为什么ExecutorService接口(interface)没有实现AutoCloseable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393417/