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

后端 未结 3 1377
甜味超标
甜味超标 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<String> task = new FutureTask<String>(new Callable<String>() {
    
        @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.

    0 讨论(0)
  • 2021-02-12 14:27

    My question is what does cancel do if mayInterruptIfRunning is false? how does it cancel or stop the task from executing if it has already been run?

    If the task has already started running, and mayInterruptIfRunning is false, then there is nothing to be done. In Java, interrupting a thread is considered to be the only safe way of stopping it short of completion - and even that requires the task to "comply" by checking for interruption at some implementation-specific interval.

    Related: How do you kill a thread in Java?

    0 讨论(0)
  • 2021-02-12 14:32

    nothing will be done if the task has already started and mayInterruptIfRunning is false,

    below is the cancel()

    public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }
    

    we can see that if mayInterruptIfRunning is false,cancel() just change state from NEW to CANCELLED and return false,nothing else will be done

    0 讨论(0)
提交回复
热议问题