如何阻止Callable提交给ExecutorService

如何阻止Callable提交给ExecutorService

本文介绍了如何阻止Callable提交给ExecutorService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个示例应用程序来测试 Callable ExecutorService 接口。

I'm trying to implement a sample application to test Callable and ExecutorService interfaces.

在我的应用程序中,我声明:

In my app I have declared:

ExecutorService exSvc = Executors.newSingleThreadExecutor();

然后:

Future<Integer> test = exSvc.submit(
    new Callable<Integer>() {
        public Integer call() {
            for(int i = 0; i < 1000; i++){
                System.out.println(i);
            }
            return 1;
        }
    });

现在我试图在终止之前停止进程,我正在使用 exSvc.shutdownNow()但它不起作用。

Now I'm trying to stop the process before it terminate, I'm using exSvc.shutdownNow() but it doesn't work.

优雅地停止经典的线程我通常使用某种条件变量。这是跟随 ExecutorService 的常见方法?

To stop gracefully a classical Thread I usually use some kind of condition variable. Which is a common approach to follow with ExecutorService?

推荐答案

Future.cancel(true) ExecutorService.shutdownNow()使用线程中断。只要您不在任务中进行不间断的阻塞调用,您只需要正确处理中断条件,如下所示:

Future.cancel(true) and ExecutorService.shutdownNow() use thread interruption. As long as you don't make uninterruptable blocking calls in your task, all you need is to handle interrupted condition correctly, something like this:

for(int i = 0; i < 1000; i++){
    // Uses isInterrupted() to keep interrupted status set
    if (Thread.currentThread().isInterrupted()) {
        // Cannot use InterruptedException since it's checked
        throw new RuntimeException();
    }
    System.out.println(i);
}

如果您进行不间断的阻止呼叫(例如网络IO),事情会变得更多复杂的,您需要以某种方式手动中断它们,例如,通过关闭底层套接字。

If you make uninterruptable blocking calls (such as network IO), things become more complex, you need to interrupt them manually somehow, for example, by closing the underlying sockets.

这篇关于如何阻止Callable提交给ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:53