线程池的工作原理
首先任务进来看有没有核心线程数,如果有则分配核心线程数,如果没有核心线程数可用则判断队列能不能存,如果队列能存则存到队列中去,等待核心线程释放后从队列中拿,如果队列中也存不下,则看有没有空闲线程,如果有空闲线程则启动空闲线程去拿,如果空闲线程没有则拒绝。
特殊情况:如果核心线程数为0,队列可以存放的下(不管有没有满),此时不会等待核心线程,直接会启动空闲线程执行task。空闲线程执行完后,如果超过保活时间还没接到新任务,就关闭线程。
线程池代码示例
static ThreadPoolExecutor threadPoolExecutor;
public static void main(String[] args) throws InterruptedException, ExecutionException {
// threadPoolExecutor = new ThreadPoolExecutor(0,1000,
// 3, TimeUnit.SECONDS,
// new ArrayBlockingQueue<>(98));
threadPoolExecutor = new ThreadPoolExecutor(1,3,
3, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(98));
AtomicInteger count = new AtomicInteger(0);
for (int i = 0; i <100 ; i++) {
threadPoolExecutor.execute(() -> {
log.debug("[{}]worker thread size[{}]", count.getAndIncrement(), threadPoolExecutor.getPoolSize()); //99时poolSize=1,98时poolSize=2
});
}
}
构造方法结构:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
ThreadPoolExecutor的execute()源码解读
public class ThreadPoolExecutor extends AbstractExecutorService {
// 高3位存状态、低27位存线程数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//工作线程集合
private final HashSet<Worker> workers = new HashSet<Worker>();
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// workerCountOf(c) 获取工作线程数量
// 工作线程数小于核心线程数,即corePoolSize>0且有可用的
// 如果corePoolSize=0时,wc等于大于0,此时if不会进
if (workerCountOf(c) < corePoolSize) { // 1366行
//创建核心线程,添加工作线程到集合并启动,然后返回true
//实例化一个线程,然后把任务分配给这个线程,并且把这个线程添加到workers,然后执行start()、执行JDK的run()、执行我们自己的run(),然后去队列获取task,没有则阻塞
//core为true,用于比较wc是否大于等于核心线程数
if (addWorker(command, true))
return;
c = ctl.get();
}
//当核心线程数满了时,才执行到这里,放入队列
//isRunning(c)线程池状态时running的
//workQueue.offer(command)往队列中提供(put)当前任务,入队成功返回true
if (isRunning(c) && workQueue.offer(command)) { //1371行
int recheck = ctl.get();
//防止线程池被停掉,如果不是running就remove当前任务
if (! isRunning(recheck) && remove(command))
reject(command);
//判断当前工作线程是否为0,但核心线程只要一启动就不会停止,所以有核心线程数时这里也不满足
//如果corePoolSize=0时,第一个任务进来wc=0,else if满足
else if (workerCountOf(recheck) == 0)
// 任务先放队列,firstTask=null, core=false
//firstTask为null表示启动idle线程,反之是启动核心线程
//core为false,用于比较wc是否大于等于最大线程数
addWorker(null, false); //1376行
}
//核心线程满了、队列也添加不进去了,else if条件成立
else if (!addWorker(command, false))
reject(command);
}
private boolean addWorker(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()))
return false;
for (;;) {
int wc = workerCountOf(c);
//wc >= CAPACITY 工作线程大于等于最大线程,几乎不可能,所以为false
if (wc >= CAPACITY ||
// 工作线程数小于核心线程数,即corePoolSize>0且有可用的时,core为true
//core为true,wc>=corePoolSize为false
//core为false,wc>=maximumPoolSize为false
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 工作线程数+1,结束死循环
if (compareAndIncrementWorkerCount(c)) //919行
break retry;
c = ctl.get(); // Re-read ctl
if (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 = new Worker(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()) // precheck that t is startable
throw new IllegalThreadStateException();
//放入工作线程集合
workers.add(w); //947行
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;
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//有核心线程时task != null,task直接分配给核心线程数
//无核心线程时,从队列里拿
while (task != null || (task = getTask()) != null) {
w.lock();
if ((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; throw new Error(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);
// Are workers subject to culling?
//没有设置核心线程数超时时间,所以allowCoreThreadTimeOut为false
//工作线程数小于核心线程数时,返回false,反之返回true
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
//工作线程数大于核心线程数时,timed=true
//执行poll(),队列为空会在保活时间内阻塞,超时后线程执行完(即回收)
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
//工作线程数小于等于核心线程数时,timed=false,
//执行take(),队列为空会一直阻塞,等待新任务来临,所以核心线程一直不会被销毁
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}