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

标签 java multithreading interrupt future

来自 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/

相关文章:

arduino - 如何让 LED 每 n 秒闪烁一次而不会出现延迟?

c - ATmega88 中断服务程序执行两次

java - 如何更改从/usr/libexec/java_home 返回的 Mac OS 的默认 Java VM

java - 在运行中停止播放剪辑

ruby-on-rails - Rails-将数据从后台作业传递到主线程

c - thrd_busy 和 mtx_lock()/mtx_timedlock()

java - 模型可以观察 View 吗?

java - 如何将命名参数与 CONTAINS 一起使用

java - 如何生成多个圆形并使这些形状沿着框架向下移动

java - JNI 代码在 Windows XP 中工作正常,但在 Windows 7 中崩溃