一、前言
线程池主要由以下4个核心组件组成。
- 线程池管理器:用于创建并管理线程池
- 工作线程:线程池中执行具体任务的线程
- 任务接口:用于定义工作线程的调度和执行策略,只有线程实现了该接口,线程中的任务才能被线程池调度
- 任务队列:放待处理的任务,新的任务将会不断被加入队列中,执行完成的任务将从队列中移除
二、ThreadPoolExecutor
如下是线程池的构造方法
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.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
其中具体参数含义为:
1.corePoolSize:线程池中核心线程的数量
2.maximumPoolSize:线程池中最大线程的数量
3.keepAliveTime:当线程数量超过corePoolSize时,空闲线程的存活时间
4.unit:keepAliveTime的时间单位
5.workQueue:任务队列,被提交但尚未被执行的任务存放的地方
6.threadFactory:线程工厂,用于创建线程,可使用默认的线程工厂或自定义线程工厂
7.handler:由于任务过多或其他原因导致线程池无法处理时的任务拒绝策略
三、构造函数参数解析
编写测试类如下:
public class ThreadPoolSerialTest { public static void main(String[] args) { //核心线程数 int corePoolSize = 2; //最大线程数 int maximumPoolSize = 4; //超过corePoolSize线程数量的线程最大空闲时间 long keepAliveTime = 2; //以秒为时间单位 TimeUnit unit = TimeUnit.SECONDS; //创建工作队列,用于存放提交的等待执行任务 BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2); ThreadPoolExecutor threadPoolExecutor = null; try { // 1.创建线程池 threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.AbortPolicy()); // 2.循环提交任务 for (int i = 0; i < 6; i++) { //提交任务的索引 final int index = (i+1); threadPoolExecutor.submit(()->{ //线程打印输出 System.out.println("大家好,我是线程:"+index); try { //模拟线程执行时间,10s Thread.sleep(100<a style="color:transparent">来@源gao*daima.com搞@代#码网</a>00); System.out.println("线程:"+index+"运行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } }); //每个任务提交后休眠500ms再提交下一个任务,用于保证提交顺序 Thread.sleep(500); } } catch (InterruptedException e) { e.printStackTrace(); } finally { // 3.关闭线程池 threadPoolExecutor.shutdown(); } } }