Future.cancel(false)为执行中的任务返回true

Jok*_*ker 3 java future

在我看来,Future.cancel(false)只有在实际上可以阻止任务执行时才返回true.

但是从下面的代码我们可以看出它是矛盾的.

由于任务是癌症,它不应该打印 "Not expecting this statement!!!"

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        final boolean[] canceled = { false };
        ScheduledFuture<?> future = executor.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    if (canceled[0])
                        System.out.println("Not expecting this statement!!!");
                } catch (InterruptedException e) {
                }
            }
        }, 0, TimeUnit.SECONDS);
        Thread.sleep(100);
        canceled[0] = future.cancel(false);

        executor.shutdown();
        executor.awaitTermination(2, TimeUnit.SECONDS);
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个程序的输出是"不期待这个声明!!!"

有人可以解释这种行为.

shi*_*zhz 5

因为你canceled[0] = future.cancel(false);用参数调用false.来自javadoc Future.cancel:

如果任务已经启动,则mayInterruptIfRunning参数确定执行此任务的线程是否应该在尝试停止任务时被中断.

@param mayInterruptIfRunning {@code true}如果执行此任务的线程应该被中断; 否则,允许完成正在进行的任务

当你打电话时cancel,你的任务已经开始并允许它完成,所以取消操作实际上是成功的并且返回true,如果你打电话canceled[0] = future.cancel(true);,你将看不到输出.