publicvoidexecute(Runnable command){if(command == null)thrownewNullPointerException();/*
* 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){//如果当前线程数小于corePoolSize,新建线程执行任务//addWorker的第二个参数的含义是线程上限是根据corePoolSize(true)还是maximumPoolSize(false)来判断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)//当前线程数为0,新建一个线程addWorker(null,false);}elseif(!addWorker(command,false))//当前线程数不小于corePoolSize,并且添加阻塞队列失败//新建线程失败,执行拒绝策略reject(command);}//创建线程执行任务的方法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{//将firstTask封装为worker
w =newWorker(firstTask);final Thread t = w.thread;if(t != null){final ReentrantLock 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){//启动线程,调用work中的run方法
t.start();
workerStarted =true;}}}finally{if(! workerStarted)addWorkerFailed(w);}return workerStarted;}//执行任务的方法finalvoidrunWorker(Worker w){
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock();// allow interruptsboolean completedAbruptly =true;try{//如果task为null,调用getTask方法获取任务while(task != null ||(task =getTask())!= null){
w.lock();// 是否中断线程的判断// If pool is stopping, ensure thread is interrupted;// if not, ensure thread is not interrupted. This// requires a recheck in second case to deal with// shutdownNow race while clearing interruptif((runStateAtLeast(ctl.get(), STOP)||(Thread.interrupted()&&runStateAtLeast(ctl.get(), STOP)))&&!wt.isInterrupted())
wt.interrupt();try{beforeExecute(wt, task);
Throwable thrown = null;try{
task.run();}catch(RuntimeException x){
thrown = x;throw x;}catch(Error x){
thrown = x;throw x;}catch(Throwable x){
thrown = x;thrownewError(x);}finally{afterExecute(task, thrown);}}finally{
task = null;
w.completedTasks++;
w.unlock();}}
completedAbruptly =false;}finally{processWorkerExit(w, completedAbruptly);}}//获取任务的接口private Runnable getTask(){boolean timedOut =false;// Did the last poll() time out?for(;;){int c = ctl.get();int rs =runStateOf(c);// Check if queue empty only if necessary.if(rs >= SHUTDOWN &&(rs >= STOP || workQueue.isEmpty())){decrementWorkerCount();return null;}int wc =workerCountOf(c);//timed变量用于超时控制,allowCoreThreadTimeOut默认是false//核心线程不超时,非核心线程会超时// Are workers subject to culling?boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;if((wc > maximumPoolSize ||(timed && timedOut))&&(wc >1|| workQueue.isEmpty())){if(compareAndDecrementWorkerCount(c))return null;continue;}try{
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS):
workQueue.take();if(r != null)return r;
timedOut =true;}catch(InterruptedException retry){
timedOut =false;}}}