public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); if (workerCountOf(c) < corePoolSize) {//当小于核心线程数的时候创建新线程 if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) {//核心线程数满,尝试入队 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); }
... //入队操作,如果非EagerThreadPool则抛出错误 public boolean force(Runnable o) { if ( parent==null || parent.isShutdown() ) throw new RejectedExecutionException(sm.getString("taskQueue.notRunning")); return super.offer(o); //forces the item onto the queue, to be used if the task is rejected }
@Override public boolean offer(Runnable o) { //parent为null,则无需干预线程池行为,使用默认行为即可 if (parent==null) return super.offer(o); //当线程池线程数满直接放进队列 if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o); //getSubmittedCount是Tomcat扩展方法,获取已提交但未完成的任务数量,这里判断说明有空闲线程,那么无需新建线程,丢尽队列等待调度即可 if (parent.getSubmittedCount()<=(parent.getPoolSize())) return super.offer(o); //当前线程数量是否已满,未满则返回false使线程池创建新线程 if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false; return super.offer(o); } }