如果没有中断,Future.cancel()会怎么做?
来自Future.cancel()上的java文档
boolean cancel(boolean mayInterruptIfRunning)
尝试取消执行此任务。 如果任务已完成,已取消或由于某些其他原因无法取消,则此尝试将失败。 如果成功,并且在调用cancel时此任务尚未启动,则此任务永远不会运行。 如果任务已经启动, 则mayInterruptIfRunning参数确定执行此任务的线程是否应该在尝试停止任务时被中断 。
我的问题是,如果mayInterruptIfRunning为false,取消会怎么做?
如果任务已经运行,它如何取消或停止执行?
如果没有打断它就会简单地告诉未来它被取消了。 您可以通过isCancelled()
检查,但如果不手动检查则没有任何反应。
下面的示例代码显示了如何执行此操作。
private static FutureTask task = new FutureTask (new Callable () { @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次迭代后告知停止。 它将继续睡觉(如果你打断它就不会睡觉),然后完成。
我的问题是,如果mayInterruptIfRunning为false,取消会怎么做? 如果任务已经运行,它如何取消或停止执行?
如果任务已经开始运行,并且mayInterruptIfRunning
为false
,则无需执行任何操作。 在Java中,中断线程被认为是阻止它完成的唯一安全方法 – 甚至要求任务通过在特定实现的特定间隔检查中断来“遵守”。
相关: 如何在Java中杀死一个线程?
如果任务已经启动并且mayInterruptIfRunning为false,则不会执行任何操作,
下面是取消()
public boolean cancel(boolean mayInterruptIfRunning) { if (state != NEW) return false; if (mayInterruptIfRunning) { if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING)) return false; Thread t = runner; if (t != null) t.interrupt(); UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state } else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED)) return false; finishCompletion(); return true; }
我们可以看到,如果mayInterruptIfRunning为false,则cancel()只是将状态从NEW更改为CANCELED并返回false,则不会执行任何其他操作