gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:04:06 24 4
gpt4 key购买 nike

在我看来,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);
}
}

不幸的是,这个程序的输出是“没想到这个语句!!!”

有人能解释一下这种行为吗。

最佳答案

因为您使用参数 false 调用了 canceled[0] = future.cancel(false);。来自 Future.cancel 的 javadoc:

If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

@param mayInterruptIfRunning {@code true} if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete

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

关于java - Future.cancel(false) 为执行中的任务返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com