java – 为什么ExecutorService接口不实现AutoCloseable?

栏目: Java · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自: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?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Neural Networks for Applied Sciences and Engineering

Neural Networks for Applied Sciences and Engineering

Samarasinghe, Sandhya / CRC Pr I Llc / 2006-9 / $ 118.59

In response to the exponentially increasing need to analyze vast amounts of data, Neural Networks for Applied Sciences and Engineering: From Fundamentals to Complex Pattern Recognition provides scient......一起来看看 《Neural Networks for Applied Sciences and Engineering》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具