privatebooleanaddWorker(RunnablefirstTask,booleancore){// 使用 CAS 来增加当前线程数retry:for(;;){...for(;;){intwc=workerCountOf(c);if(wc>=CAPACITY||wc>=(core?corePoolSize:maximumPoolSize))returnfalse;if(compareAndIncrementWorkerCount(c))breakretry;c=ctl.get();// Re-read ctlif(runStateOf(c)!=rs)continueretry;}}...try{// 创建新的 workerw=newWorker(firstTask);finalThreadt=w.thread;if(t!=null){finalReentrantLockmainLock=this.mainLock;mainLock.lock();try{intrs=runStateOf(ctl.get());// 添加到 workers 中if(rs<SHUTDOWN||(rs==SHUTDOWN&&firstTask==null)){if(t.isAlive())// precheck that t is startablethrownewIllegalThreadStateException();workers.add(w);ints=workers.size();// 更新当前最大线程数if(s>largestPoolSize)largestPoolSize=s;workerAdded=true;}}finally{mainLock.unlock();}// 添加成功,启动线程if(workerAdded){t.start();workerStarted=true;}}}finally{...}returnworkerStarted;}
// 获取任务,如果为 null,当前线程就要终止privateRunnablegetTask(){booleantimedOut=false;// Did the last poll() time out?for(;;){intc=ctl.get();intrs=runStateOf(c);// 如果 SHUTDOWN 状态,任务队列为空,应该减少 workerif(rs>=SHUTDOWN&&(rs>=STOP||workQueue.isEmpty())){decrementWorkerCount();returnnull;}intwc=workerCountOf(c);// 控制是否要结束线程booleantimed=allowCoreThreadTimeOut||wc>corePoolSize;// timedOut 为 true,表示没有任务了if((wc>maximumPoolSize||(timed&&timedOut))&&(wc>1||workQueue.isEmpty())){// CAS 减少 workerif(compareAndDecrementWorkerCount(c))returnnull;continue;}try{// 获取任务,对于非核心线程是 poll 方法, 对核心线程是 take 方法Runnabler=timed?workQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS):workQueue.take();if(r!=null)returnr;timedOut=true;}catch(InterruptedExceptionretry){timedOut=false;}}}