[英]Shutdown executor without executorService in Java
Is there a way to shutdown an Executor
in Java without first casting it to ExecutorService
? 有没有一种方法可以先关闭Java中的Executor
,而无需先将其强制转换为ExecutorService
? Basically i have a class called Exx
that implements Executor
. 基本上我有一个叫做Exx
的类,它implements Executor
。 I want to shutdown Exx. 我想关闭Exx。 How would I do that? 我该怎么做? Essentially, I need to know how to shutdown an Executor
. 本质上,我需要知道如何关闭Executor
。
EDIT: Example: 编辑:示例:
class Exx implements Executor{
@Override
public void execute(Runnable r) {
new Thread(r).start();
}
}
An Executor
by nature of the specific interface is not something that needs to be shutdown. 一个Executor
由特定接口的性质是不是需要被关闭。 For instance, here is the most basic implementation of Executor
. 例如,这是Executor
最基本的实现。
class NearlyPointlessExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
Clearly in the code above, there is nothing so complicated that anything need be shutdown, yet the provided class adheres completely to the Executor
interface. 显然,在上面的代码中,没有什么复杂的事情需要关闭任何东西,但是所提供的类完全遵循Executor
接口。
If your implementation does need to be shutdown, then your options are either to make your own interface or implement ExecutorService
. 如果您的实现确实需要关闭,那么您可以选择创建自己的接口或实现ExecutorService
。
Update for question edit: 更新问题编辑:
In the case of the provided code, it would not be possible to shutdown the Threads being created because no reference to them is kept in a collection. 对于提供的代码,将无法关闭正在创建的线程,因为在集合中没有保留对它们的引用。
However, there is a solution, the implementation provided is essentially the same as the one provided by using: Executors.newCachedThreadPool . 但是,有一种解决方案,提供的实现与使用的实现基本相同: Executors.newCachedThreadPool 。 Discard your own implementation and use this one instead. 放弃自己的实现,而改用此实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.