目录
线程池
线程池,就是有一定数量线程的池子,池子中的线程可以多次使用,这可以减少创建和销毁线程的次数,从而达到节约运行时间和系统资源的目的。ThreadPoolExecutor是Java中的一个ExecutorService。
线程池的配置
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize
核心线程数,默认为1。
该参数的设置主要看使用场景,在CPU密集型的场景中使用,corePoolSize = CPU 核数 + 1;在IO密集型的场景中使用,corePoolSize = CPU 核数 * 2
在提交一个任务到线程池中时,如果池中线程数量小于核心线程数,线程池会创建一个线程来执行任务,即使有空闲线程存在也会创建新线程。
默认情况下,线程池只有在有任务时才会创建线程,prestartAllCoreThreads()方法,可以实现预先创建并启动好所有核心线程
/**
* Starts all core threads, causing them to idly wait for work. This
* overrides the default policy of starting core threads only when
* new tasks are executed.
*
* @return the number of threads started
*/
public int prestartAllCoreThreads() {
int n = 0;
while (addWorker(null, true))
++n;
return n;
}
maximumPoolSize
线程池可创建的最大线程数,默认为Integer.MAX_VALUE
一般设置为和核心线程数一样
如果队列已满,线程池将创建新的线程来处理任务,直到线程池中的线程数量达到设置的最大线程数量。
keepAliveTime
空