1.2 线程池-执行任务

1.2 线程池-执行任务

prestartAllCoreThreads

Tomcat在启动线程池的时候就已经初始化了所有核心线程,调用了addWorker方法

public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true))
            ++n;
        return n;
    }

而 execute(如下),也是调用了addWorker这个方法添加了一堆任务,这看起来就是核心方法

 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
         * 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) {
		//添加成功就直接返回了
		 //addWorker第二个参数 表示创建的是否核心线程
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
		//走到这里说明上面没成功 说明有其他线程也在添加任务,导致核心线程达到数量了
		//这一句判断是否运行中,并且向队列里添加任务,如果不成功(比如队列满了)就走else
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
			//再次校验 如果线程池状态不是运行中 并且删除任务成功了,走拒绝逻辑
            if (! isRunning(recheck) && remove(command))
                reject(command);
			//否则 如果线程数量为0 走创建非核心线程逻辑?什么场景会走到这里再分析
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
		//这一句走创建非核心线程逻辑
        else if (!addWorker(command, false))
            reject(command);
    }
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 1.2 线程池-执行任务