What does Future.cancel() do if not interrupting?

后端 未结 3 1390
甜味超标
甜味超标 2021-02-12 13:54

From java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This

3条回答
  •  無奈伤痛
    2021-02-12 14:20

    If it is not interrupting it will simply tell the future that is is cancelled. You can check that via isCancelled() but nothing happens if you don't check that manually.

    Below example code shows how you could do it.

    private static FutureTask task = new FutureTask(new Callable() {
    
        @Override
        public String call() throws Exception {
            while (!task.isCancelled()) {
                System.out.println("Running...");
                Thread.sleep(1000);
            }
            return "The End";
        }
    
    });
    
    public static void main(String[] args) throws InterruptedException {
        new Thread(task).start();
        Thread.sleep(1500);
        task.cancel(false);
    }
    

    The task is started, and after 1.5 iterations told to stop. It will continue sleeping (which it would not if you interrupted it) and then finish.

提交回复
热议问题