• ThreadPoolExecutor 中为什么WorkQueue会在corePoolSize满了之后入队


    简介

    看别人的博客, 不清楚为什么会入队.

    code

       public void execute(Runnable command) {
            if (command == null)
                throw new NullPointerException();
            /*
             * Proceed in 3 steps:
             *
             * 1. If fewer than corePoolSize threads are running, try to 简单来说就是如果小于corePoolSize直接创建新线程
             * start a new thread with the given command as its first
             * task.  The call to addWorker atomically checks runState and
             * workerCount, and so prevents false alarms that would add
             * threads when it shouldn't, by returning false.
             *
             * 2. If a task can be successfully queued, then we still need 
             * to double-check whether we should have added a thread
             * (because existing ones died since last checking) or that
             * the pool shut down since entry into this method. So we
             * recheck state and if necessary roll back the enqueuing if
             * stopped, or start a new thread if there are none.
             *
             * 3. If we cannot queue task, then we try to add a new
             * thread.  If it fails, we know we are shut down or saturated
             * and so reject the task.
             */
            int c = ctl.get();
            if (workerCountOf(c) < corePoolSize) {
                if (addWorker(command, true))
                    return;
                c = ctl.get();
            }
            if (isRunning(c) && workQueue.offer(command)) { // 反正只要正在运行着, 就会直接入队了. 入队也会有四种判定方式, 一种是直接提交队列, 就是大于corePoolSize, 小于maxPoolSize创建新的线程. 一种是无界队列, 反正来的任务都等着执行, 还有有界, 就是大于corePoolSize, 且大于设定的有界个数, 才会去创建新的线程. 
                int recheck = ctl.get();
                if (! isRunning(recheck) && remove(command))
                    reject(command);
                else if (workerCountOf(recheck) == 0)
                    addWorker(null, false);
            }
            else if (!addWorker(command, false))
                reject(command);
        }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    KindEditor简单的Demo使用
    动态从数据库读取菜单(ASP.NET版)
    完全卸载sql2005
    关于在xp(sp3 专业版)下安装sql2005开发版图解
    新手上路Tomcat 7.x和JDK的配置
    关于IE6幽灵字体
    【译】写个好的 CLI 程序
    【译】通过 Rust 学习解析器组合器 — Part 1
    【译】PHP 内核 — zval 基础结构
    【译】PHP 内核 — 字符串管理
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/15131843.html
Copyright © 2020-2023  润新知