线程池的规则与参数:
1. corePoolSize:核心线程数
- 核心线程会一直存活,及时没有任务需要执行
- 当线程数小于核心线程数时,即使有线程空闲,线程池也会优先创建新线程处理
- 设置allowCoreThreadTimeout=true(默认false)时,核心线程会超时关闭
2. queueCapacity:任务队列容量(阻塞队列)
- 当核心线程数达到最大时,新任务会放在队列中排队等待执行
3. maxPoolSize:最大线程数
- 当线程数>=corePoolSize,且任务队列已满时。线程池会创建新线程来处理任务
- 当线程数>=corePoolSize 且队列未满时,不再创建新线程
- 当线程数=maxPoolSize,且任务队列已满时,线程池会拒绝处理任务而抛出异常
4. keepAliveTime:非核心线程空闲时间
- 当线程空闲时间达到keepAliveTime时,线程会退出,直到线程数量=corePoolSize
5. allowCoreThreadTimeout:允许核心线程超时
- 默认为false;设置为true时,核心线程也会在keepAliveTime后退出。
6. rejectedExecutionHandler:任务拒绝处理器
- 当线程数已经达到maxPoolSize,切队列已满,会拒绝新任务
- shutdown()后的等待期内提交的任务,会被拒绝
几类型线程池
1. FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), threadFactory);}
核心池等于最大池大小,队列无界;核心线程不会退出。
2. SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue())); }
核心池等于最大池=1,队列无界;保证任务串行执行,当线程因为异常终止,会启动新线程执行;该线程不会超时退出。
3. CachedThreadPool
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue(), threadFactory);}
核心池大小是0,最大池大小无上界,队列无界;线程60s超时退出。适合短期执行的大量任务。SynchronousQueue是一个容量只有1的阻塞队列。
4. ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize);}public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());}
使用DelayQueue实现定时执行。