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

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条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败