gpt4 book ai didi

java - 如果不中断,Future.cancel() 会做什么?

转载 作者:太空狗 更新时间:2023-10-29 22:46:33 30 4
gpt4 key购买 nike

来自 java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. 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.

我的问题是,如果 mayInterruptIfRunning 为 false,cancel 会做什么?
如果任务已经运行,它如何取消或停止执行?

最佳答案

如果它没有中断,它会简单地告诉被取消的 future 。您可以通过 isCancelled() 查看但如果您不手动检查,则什么也不会发生。

下面的示例代码展示了如何做到这一点。

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

任务开始,并在 1.5 次迭代后被告知停止。它会继续 hibernate (如果你打断它就不会)然后结束。

关于java - 如果不中断,Future.cancel() 会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445224/

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