private static int corePoolSize = 20;
private static int maxPoolSize = 100;
private static int keepAliveTime = 0;
private static TimeUnit timeUnit = TimeUnit.MINUTES;
private static BlockingQueue blockingQueue = new ArrayBlockingQueue<>(9999);
private static RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
private static ThreadPoolExecutor pool =
new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, blockingQueue, handler);
- corePoolSize: 线程池的核心线程数(公司骨干成员)
- maxPoolSize: 线程大容量(公司最多能容纳这些人)
- keepAliveTime: 非核心线程存活时间
- timeUnit: 时间单位(秒还是分)
- blockingQueue: 阻塞队列 , 当线程数达到核心线程数时,任务就会在阻塞队列中等待,若等待的任务数大于指定队列的大小,则开启非核心线程进行执行任务, 最maxPoolSize个
- RejectedExecutionHandler: 拒绝策略 当线程数量达到非核心线程数, 并且队列中的等待的任务也满了, 那么则执行拒绝策略
其他决绝策略, 点击查看
项目统一用一个线程池
public final class ThreadPoolFactory {
private static volatile ThreadPoolExecutor threadPoolExecutor = null;
private static final int CORE_POOL_SIZE = 0;
private static final int MAX_MUM_POOL_SIZE = 1000;
private static final long KEEP_ALIVE_TIME = 2;
private static final TimeUnit UNIT = TimeUnit.MINUTES;
private static final int CAPACITY = 20;
private static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();
private ThreadPoolFactory() {
}
public static ThreadPoolExecutor getInstance() {
if (threadPoolExecutor == null) {
synchronized (ThreadPoolFactory.class) {
if (threadPoolExecutor == null) {
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_MUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, new ArrayBlockingQueue<>(CAPACITY), HANDLER);
}
}
}
return threadPoolExecutor;
}
}