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 如果运行的线程数少于 corePoolSize,启动一个新线程作为其第一个任务。对 addWorker 的调用以原子方式检查 runState 和 workerCount,从而通过返回 false 来防止在不应该添加线程时出现误报。
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. *如果任务可以成功排队,那么我们仍然需要仔细检查是否应该添加一个线程(因为自上次检查以来现有线程已死亡)或池自进入此方法后关闭。因此,我们重新检查状态,并在必要时在停止时回滚入队,如果没有则启动一个新线程。
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. * 如果我们无法排队任务,那么我们尝试添加一个新线程。如果它失败了,我们知道我们已经关闭或饱和,因此拒绝该任务。
//前3位代表状态 后29位代表线程数量privatefinalAtomicInteger ctl =newAtomicInteger(ctlOf(RUNNING,0));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);elseif(workerCountOf(recheck)==0)addWorker(null,false);}elseif(!addWorker(command,false))reject(command);
2.1 addWorker
privatebooleanaddWorker(Runnable firstTask,boolean core){
retry:for(;;){int c = ctl.get();int rs =runStateOf(c);// Check if queue empty only if necessary.if(rs >= SHUTDOWN &&!(rs == SHUTDOWN &&
firstTask ==null&&! workQueue.isEmpty()))returnfalse;for(;;){int wc =workerCountOf(c);if(wc >= CAPACITY ||
wc >=(core ? corePoolSize : maximumPoolSize))returnfalse;if(compareAndIncrementWorkerCount(c))break retry;
c = ctl.get();// Re-read ctlif(runStateOf(c)!= rs)continue retry;// else CAS failed due to workerCount change; retry inner loop}}boolean workerStarted =false;boolean workerAdded =false;Worker w =null;try{
w =newWorker(firstTask);finalThread t = w.thread;if(t !=null){finalReentrantLock mainLock =this.mainLock;
mainLock.lock();try{// Recheck while holding lock.// Back out on ThreadFactory failure or if// shut down before lock acquired.int rs =runStateOf(ctl.get());if(rs < SHUTDOWN ||(rs == SHUTDOWN && firstTask ==null)){if(t.isAlive())// precheck that t is startablethrownewIllegalThreadStateException();
workers.add(w);int s = workers.size();if(s > largestPoolSize)
largestPoolSize = s;
workerAdded =true;}}finally{
mainLock.unlock();}if(workerAdded){
t.start();
workerStarted =true;}}}finally{if(! workerStarted)addWorkerFailed(w);}return workerStarted;}