---已debug解惑---
1)传参为false,如果这个任务正在执行,它并不能够做任何对这个任务取消的操作,只能静静等待这个任务执行完成。
2)传参为true,会中断这个任务所属的线程。那么问题来了,可能这个线程随后还需要执行其他Task呢,这就意味着,取消操作会影响到所属线程随后执行的其他任务吧。
感觉设计上怪别扭的。
以下是部分源码:
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
debug了一下,并不会出现我描述的这种问题。
以ThreadPoolExecutor为例:
在worker轮询从阻塞队列取出UserTask(也就是用户自定义的Runnable/Callable)的时候,捕获了
InterruptedException
异常,这就导致Worker线程清除了中断状态。也就是说,当FutureTask调用取消方法后,并不会影响其他的Task.以下为ThreadPoolExecutor的getTask()方法相关代码: