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个回答

因为代码有可能会在
[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]

在成为大牛之前,不要这么轻易怀疑源码,先思考自己有哪里没考虑周全

立即提问
相关内容推荐