0

Is there a way to shutdown an Executor in Java without first casting it to ExecutorService? Basically i have a class called Exx that implements Executor. I want to shutdown Exx. How would I do that? Essentially, I need to know how to shutdown an Executor.

EDIT: Example:

class Exx implements Executor{
    @Override
    public void execute(Runnable r) {
        new Thread(r).start();
    }       
}
4

1 回答 1

3

特定接口的Executor本质是不需要关闭的东西。例如,这里是最基本的实现Executor

class NearlyPointlessExecutor implements Executor {
    public void execute(Runnable r) {
        r.run();
    }
}

很明显,在上面的代码中,没有什么复杂到需要关闭任何东西,但提供的类完全符合Executor接口。

如果您的实现确实需要关闭,那么您的选择是创建自己的接口或实现ExecutorService

问题编辑更新:

在提供的代码的情况下,不可能关闭正在创建的线程,因为对它们的引用没有保存在集合中。

但是,有一个解决方案,提供的实现与使用提供的实现基本相同:Executors.newCachedThreadPool。放弃您自己的实现并改用这个。

于 2012-07-25T17:42:48.720 回答