通过线程池的方法重新设置核心线程数 setCorePoolSize
当最新的核心线程数小于之前的核心线程数时,则需要进行多余的线程中断
当最新的核心线程数大于之前的核心线程数,则需要逐步的增加核心线程数
源码如下:
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
int delta = corePoolSize - this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get()) > corePoolSize)
interruptIdleWorkers();
else if (delta > 0) {
// We don't really know how many new threads are "needed".
// As a heuristic, prestart enough new workers (up to new
// core size) to handle the current number of tasks in
// queue, but stop if queue becomes empty while doing so.
int k = Math.min(delta, workQueue.size());
while (k-- > 0 && addWorker(null, true)) {
if (workQueue.isEmpty())
break;
}
}
}
备注:当最新的核心线程数大于之前核心线程数时,不是一致性增加差额的线程数,而是一个一个线程添加,添加完一个再去查询任务队列是否有任务;有任务则再次添加,没有任务则就此停止