如何阻止Callable提交给ExecutorService?

dav*_*ooh 11 java multithreading

我正在尝试实现一个示例应用程序来测试CallableExecutorService接口.

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

ExecutorService exSvc = Executors.newSingleThreadExecutor();
Run Code Online (Sandbox Code Playgroud)

然后:

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

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

为了优雅地停止经典,Thread我通常使用某种条件变量.这是一种常见的跟进方法ExecutorService

axt*_*avt 17

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

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);
}
Run Code Online (Sandbox Code Playgroud)

如果你进行不间断的阻塞调用(例如网络IO),事情变得更加复杂,你需要以某种方式手动中断它们,例如,通过关闭底层套接字.