如果没有中断,Future.cancel()会怎么做? [英] What does Future.cancel() do if not interrupting?

查看:186
本文介绍了如果没有中断,Future.cancel()会怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Future.cancel上的java文档()

boolean cancel(boolean mayInterruptIfRunning)




尝试取消执行此任务。如果任务已完成,已取消或由于某些其他原因无法取消,则此尝试将失败。如果成功,并且在调用cancel时此任务尚未启动,则此任务永远不会运行。如果任务已经启动,则然后mayInterruptIfRunning参数确定执行此任务的线程是否应该被中断以尝试停止任务。

我的问题是,如果mayInterruptIfRunning为false,取消会做什么?

如果任务已经运行,它如何取消或停止执行?

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?

推荐答案

如果它没有中断,它只会告诉未来它被取消了。您可以通过 <$来查看c $ c> isCancelled() 但如果你不手动检查,则没有任何反应。

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

任务开始,1.5次迭代后告知停止。它将继续睡觉(如果你打断它就不会睡觉)然后完成。

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.

这篇关于如果没有中断,Future.cancel()会怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆