Tom*_*Tom 17 java multithreading future interrupt
boolean cancel(boolean mayInterruptIfRunning)
Run Code Online (Sandbox Code Playgroud)
尝试取消执行此任务.如果任务已完成,已取消或由于某些其他原因无法取消,则此尝试将失败.如果成功,并且在调用cancel时此任务尚未启动,则此任务永远不会运行.如果任务已经启动,则mayInterruptIfRunning参数确定执行此任务的线程是否应该在尝试停止任务时被中断.
我的问题是,如果mayInterruptIfRunning为false,取消会怎么做?
如果任务已经运行,它如何取消或停止执行?
zap*_*apl 10
如果它没有打断它就会简单地告诉未来它被取消了.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);
}
Run Code Online (Sandbox Code Playgroud)
任务开始,并在1.5次迭代后告知停止.它将继续睡觉(如果你打断它就不会睡觉),然后完成.
小智 5
如果任务已经开始并且 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;
}
Run Code Online (Sandbox Code Playgroud)
我们可以看到,如果 mayInterruptIfRunning 为 false,cancel() 只是将状态从 NEW 更改为 CANCELLED 并返回 false,则不会执行其他操作