xsxjb 2011-03-16 14:47
浏览 462
已采纳

ThreadPoolExecutor类的execute()方法有BUG ?

本人菜鸟一只,最近看了一下ThreadPoolExecutor 类的 execute() 方法。
发现 程序中显示判断 if (runState == RUNNING && workQueue.offer(command))

在这个判断的里面有写了一个if (runState != RUNNING || poolSize == 0) 

如果第一个IF 条件成立 那么runState != RUNNING  就永远都不会成立了啊。。。。。。。请大牛们指点一二。。。。

runState变量在类中是这样定义的。volatile int runState;

 

 

ThreadPoolExecutor 类的 execute() 方法源代码如下:

    
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
            if (runState == RUNNING && workQueue.offer(command)) {
                if (runState != RUNNING || poolSize == 0)
                    ensureQueuedTaskHandled(command);
            }
            else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated
        }
    }

 

  • 写回答

2条回答 默认 最新

  • changchanghust 2011-03-16 15:52
    关注

    因为代码有可能会在
    [quote]workQueue.offer(command)[/quote]
    这里阻塞。成功插入一个任务后,可能线程池的状态已经改变,所以要再次检查runState,然后再决定是否拒绝该任务还是继续执行。
    后续的操作可以从ensureQueuedTaskHandled的注释里看到:

    [quote]Rechecks state after queuing a task. Called from execute when
    pool state has been observed to change after queuing a task. If
    the task was queued concurrently with a call to shutdownNow,
    and is still present in the queue, this task must be removed
    and rejected to preserve shutdownNow guarantees. Otherwise,
    this method ensures (unless addThread fails) that there is at
    least one live thread to handle this task[/quote]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?