How to stop a Callable submitted to ExecutorService?

前端 未结 2 1773
鱼传尺愫
鱼传尺愫 2021-02-05 23:01

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

In my app I have declared:

Execu         


        
2条回答
  •  感动是毒
    2021-02-05 23:41

    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);
    }
    

    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.

提交回复
热议问题