内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/41393417/why-does-the-executorservice-interface-not-implement-autocloseable
没有在线程执行程序上调用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,因为该服务没有像关闭一样的操作;但是两个!
如果您认为您可以善用这种自动关闭服务,则使用“委托”来编写自己的实施将是5分钟的事情!或者大概10分钟,因为你会创建一个调用shutdown()作为close操作的版本;而另一个则执行shutdownNow().
代码日志版权声明:
翻译自:http://stackoverflow.com/questions/41393417/why-does-the-executorservice-interface-not-implement-autocloseable
以上所述就是小编给大家介绍的《java – 为什么ExecutorService接口不实现AutoCloseable?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- delphi – 如何检查接口对象是否实现了另一个接口?
- SpringBoot2 API接口签名实现(接口参数防篡改)
- 接口与实现分离
- 判断Golang接口是否实现
- Python实现数据驱动接口测试
- Spring应用--实现InitializingBean接口
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。