java FutureTask的cancel(boolean mayInterruptIfRunning)方法是不是有问题啊

---已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;
    }
回复
阅读 3.9k
1 个回答

debug了一下,并不会出现我描述的这种问题。

以ThreadPoolExecutor为例:
在worker轮询从阻塞队列取出UserTask(也就是用户自定义的Runnable/Callable)的时候,捕获了InterruptedException异常,这就导致Worker线程清除了中断状态。也就是说,当FutureTask调用取消方法后,并不会影响其他的Task.

以下为ThreadPoolExecutor的getTask()方法相关代码:

try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏