初始化
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
这里有几个参数,
corePoolSize 核心线程数 一般为cpu的核心数+1
maximumPoolSize 最大线程数 一般为 cpu的核心数*2 +1
keepAliveTime 保活时间
unit 保活时间单位
workQueue 任务队列 一般为128
当任务个数未达到核心线程数时,直接在核心线程中处理任务,当任务达到核心线程数时在非核心线程中处理,当任务超过非核心线程数时,会任务排队等待,当任务超过workQueue时,会调用RejectedExecutionHandler的rejectedExecution抛出异常,当到达保活时间时非核心线程会释放,如果
public void allowCoreThreadTimeOut(boolean value) {
if (value && keepAliveTime <= 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
allowCoreThreadTimeOut = value;
if (value)
interruptIdleWorkers();
}
}
该方法设置为true时,核心线程也会被释放
几种常用的线程池初始化
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newFixedThreadPool 只有核心线程,核心线程个数固定,没有超时机制,没有队列大小限制
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newCachedThreadPool 没有核心线程,非核心线程个数未整型最大值,超时时间60s, 闲置时立刻收回,适合耗时较小的任务
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
ScheduledThreadPoolExecutor 核心数固定,非核心数个数枚限制,适合执行定时任务和具有周期性的任务
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newSingleThreadExecutor 所有任务都统一到一个线程中进行处理,没有超时,不需要考虑同步问题