publicThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue){this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);}
提交任务
publicvoidexecute(Runnable command){
int c = ctl.get();//活跃线程数小于核心线程数的话,就添加一个工作线程给入参,提前返回if(workerCountOf(c)< corePoolSize){if(addWorker(command,true))return;
c = ctl.get();}//线程池正在运转且当前任务加入工作队列//向阻塞队列加入任务,具体实现依赖于线程池初始化时传入的阻塞队列类型//对于有界队列,如果队列已满则返回falseif(isRunning(c)&& workQueue.offer(command)){
int recheck = ctl.get();//如果线程池已经不再正常运转,则先从工作队列移除当前任务并终止,然后抛出异常if(!isRunning(recheck)&&remove(command))reject(command);//如果工作线程变为0,则添加工作线程(防止并发问题)elseif(workerCountOf(recheck)==0)addWorker(null,false);}//无法进入工作队列且无法添加工作线程,则抛错elseif(!addWorker(command,false))reject(command);}
添加工作线程
private boolean addWorker(Runnable firstTask, boolean core){
retry:for(;;){
int c = ctl.get();
int rs =runStateOf(c);//线程池状态if(rs >=SHUTDOWN&&!(rs ==SHUTDOWN&& firstTask ==null&&! workQueue.isEmpty()))returnfalse;for(;;){
int wc =workerCountOf(c);if(wc >=CAPACITY||//活跃线程超出阈值
wc >=(core ? corePoolSize : maximumPoolSize))returnfalse;//尝试新增一个工作线程(这里先CAS更改统计数目)if(compareAndIncrementWorkerCount(c))break retry;
c = ctl.get();if(runStateOf(c)!= rs)//活跃线程数已经改变,此处需要重新循环添加流程continue retry;}}
boolean workerStarted =false;
boolean workerAdded =false;
Worker w =null;try{
w =newWorker(firstTask);
final Thread t = w.thread;if(t !=null){
final ReentrantLock mainLock =this.mainLock;
mainLock.lock();try{
int rs =runStateOf(ctl.get());if(rs <SHUTDOWN||(rs ==SHUTDOWN&& firstTask ==null)){if(t.isAlive())thrownewIllegalThreadStateException();//add区别于offer,在有界队列满时操作会抛异常
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;}
运行
publicvoidrun(){runWorker(this);}
final voidrunWorker(Worker w){
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask =null;
w.unlock();// allow interrupts
boolean completedAbruptly =true;try{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();returnnull;}
int wc =workerCountOf(c);// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;if((wc > maximumPoolSize ||(timed && timedOut))&&(wc >1|| workQueue.isEmpty())){if(compareAndDecrementWorkerCount(c))//CAS扣减活跃线程数returnnull;continue;}try{
Runnable r = timed ?//从任务队列取出
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS):
workQueue.take();if(r !=null)return r;
timedOut =true;}catch(InterruptedException retry){
timedOut =false;}}}
关闭线程池
//已提交任务会被执行,新提交的任务则不被允许放入任务队列。正在执行的任务会继续执行,没有被执行的被中断publicvoidshutdown(){
final ReentrantLock mainLock =this.mainLock;
mainLock.lock();try{checkShutdownAccess();advanceRunState(SHUTDOWN);interruptIdleWorkers();onShutdown();// hook for ScheduledThreadPoolExecutor}finally{
mainLock.unlock();}tryTerminate();}//将线程池的状态置为STOP,正在执行的任务被停止,没被执行的任务返回public List<Runnable>shutdownNow(){
List<Runnable> tasks;
final ReentrantLock mainLock =this.mainLock;
mainLock.lock();try{checkShutdownAccess();advanceRunState(STOP);interruptWorkers();
tasks =drainQueue();}finally{
mainLock.unlock();}tryTerminate();return tasks;}