当前位置:网站首页>线程池 ThreadPoolExecutor 详解
线程池 ThreadPoolExecutor 详解
2022-07-29 18:50:00 【闻说社】
一 为什么要使用线程池
对于操作系统而言,创建一个线程的代价是十分昂贵的, 需要给它分配内存、列入调度,同时在线程切换时要执行内存换页,清空 CPU 缓存,切换回来时还要重新从内存中读取信息,破坏了数据的局部性。因此在并发编程中,当线程创建过多时,会影响程序性能,甚至引起程序崩溃。
而线程池属于池化管理模式,具有以下优点:
- 降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的性能消耗。
- 提高响应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。
- 提高线程的可管理性:能够对线程进行统一分配、调优和监控。
二 线程池原理详解
2.1 线程池核心组成
线程池包含 3 个核心部分:
- 线程集合:核心线程和工作线程
- 阻塞队列:用于待执行任务排队
- 拒绝策略处理器:阻塞队列满后,对任务处理进行
2.2 Execute 原理
当一个新任务提交至线程池之后,线程池的处理流程如下:
- 首先判断当前运行的线程数量是否小于 corePoolSize。如果是,则创建一个工作线程来执行任务;如果都在执行任务,则进入步骤 2。
- 判断 BlockingQueue 是否已经满了,若没满,则将任务放入 BlockingQueue;若满了,则进入步骤 3。
- 判断当前运行的总线程数量是否小于 maximumPoolSize,如果是则创建一个新的工作线程来执行任务。
- 否则交给 RejectedExecutionHandler 来处理任务。
当 ThreadPoolExecutor 创建新线程时,通过 CAS 来更新线程池的状态 ctl。
三 线程池的使用
线程池的使用主要分为以下三个步骤:
3.1 创建线程池
3.1.1 自定义线程池
线程池的真正实现类是 ThreadPoolExecutor,其构造方法有如下 4 种:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
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
(必需)线程池中的核心线程数,当提交一个任务时,线程池创建一个新线程执行任务,直到当前线程数等于 corePoolSize, 即使有其他空闲线程能够执行新来的任务, 也会继续创建线程;如果当前线程数为 corePoolSize,继续提交的任务被保存到阻塞队列中,等待被执行;如果执行了线程池的 **prestartAllCoreThreads()**方法,线程池会提前创建并启动所有核心线程。workQueue
(必需)用来保存等待被执行的任务的阻塞队列。ArrayBlockingQueue
: 基于数组结构的有界阻塞队列,按 FIFO 排序任务;LinkedBlockingQueue
: 基于链表结构的阻塞队列,按 FIFO 排序任务,吞吐量通常要高于 ArrayBlockingQueue;SynchronousQueue
: 一个不存储元素的阻塞队列,每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于 LinkedBlockingQueue;PriorityBlockingQueue
: 具有优先级的无界阻塞队列;
maximumPoolSize
(必需)线程池中能容纳的最大线程数。如果当前阻塞队列满了,且继续提交任务,则创建新的线程执行任务,前提是当前线程数小于 maximumPoolSize;当阻塞队列是无界队列, 则 maximumPoolSize 则不起作用, 因为无法提交至核心线程池的线程会一直持续地放入 workQueue。keepAliveTime
(必需)线程闲置超时时长。如果超过该时长,非核心线程就会被回收。如果将 allowCoreThreadTimeout 设置为 true 时,核心线程也会超时回收。unit
(必需)keepAliveTime 的单位,常用的有:TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)、TimeUnit.MINUTES(分)threadFactory
(可选)创建线程的工厂,通过自定义的线程工厂可以给每个新建的线程设置一个具有识别度的线程名。默认为 DefaultThreadFactoryhandler
(可选)线程池的饱和策略,当阻塞队列满了,且没有空闲的工作线程,如果继续提交任务,必须采取一种策略处理该任务,线程池提供了 4 种策略:AbortPolicy
: 直接抛出异常,默认策略;CallerRunsPolicy
: 用调用者所在的线程来执行任务;DiscardOldestPolicy
: 丢弃阻塞队列中靠最前的任务,并执行当前任务;DiscardPolicy
: 直接丢弃任务; 也可以根据应用场景实现 RejectedExecutionHandler 接口,自定义饱和策略,如记录日志或持久化存储不能处理的任务。
3.1.2 功能线程池
除了调用 ThreadPoolExecutor 自定义线程池的方式,其实 Executors 也已经为我们封装好了 4 种常见的功能线程池,如下:
- 定长线程池(FixedThreadPool)
- 定时线程池(ScheduledThreadPool)
- 可缓存线程池(CachedThreadPool)
- 单线程化线程池(SingleThreadExecutor)
定长线程池(FixedThreadPool)
- 特点:只有核心线程,线程数量固定,执行完立即回收,任务队列为链表结构的有界队列。
- 应用场景:控制线程最大并发数。
- 使用示例:
// 1. 创建定长线程池对象 & 设置线程池线程数量固定为 3
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
// 2. 创建好 Runnable 类线程对象 & 需执行的任务
Runnable task = new Runnable(){
public void run() {
...//待执行的耗时任务
}
};
// 3. 向线程池提交任务
fixedThreadPool.execute(task);
复制代码
定时线程池(ScheduledThreadPool)
- 特点:核心线程数量固定,非核心线程数量无限,执行完闲置 10ms 后回收,任务队列为延时阻塞队列。
- 应用场景:执行定时或周期性的任务。
- 使用示例:
// 1. 创建定时线程池对象 & 设置线程池线程数量固定为 5
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
// 2. 创建好 Runnable 类线程对象 & 需执行的任务
Runnable task =new Runnable(){
public void run() {
...//待执行的耗时任务
}
};
// 3. 向线程池提交任务
scheduledThreadPool.schedule(task, 1, TimeUnit.SECONDS); // 延迟 1s 后执行任务
复制代码
可缓存线程池(CachedThreadPool)
- 特点:无核心线程,非核心线程数量无限,执行完闲置 60s 后回收,任务队列为不存储元素的阻塞队列。
- 应用场景:执行大量、耗时少的任务。
- 使用示例:
// 1. 创建可缓存线程池对象
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
// 2. 创建好 Runnable 类线程对象 & 需执行的任务
Runnable task =new Runnable(){
public void run() {
...//待执行的耗时任务
}
};
// 3. 向线程池提交任务
cachedThreadPool.execute(task);
复制代码
单线程化线程池(SingleThreadExecutor)
- 特点:只有 1 个核心线程,无非核心线程,执行完立即回收,任务队列为链表结构的有界队列。
- 应用场景:不适合并发但可能引起 IO 阻塞性及影响 UI 线程响应的操作,如数据库操作、文件操作等。
- 使用示例:
// 1. 创建单线程化线程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
// 2. 创建好 Runnable 类线程对象 & 需执行的任务
Runnable task =new Runnable(){
public void run() {
...//待执行的耗时任务
}
};
// 3. 向线程池提交任务
singleThreadExecutor.execute(task);
复制代码
3.1.3 功能线程池存在的问题
目前已不推荐使用功能线程池,而是通过自定义 ThreadPoolExecutor 的方式。因为直接使用功能线程池具有资源耗尽的风险。
- newFixedThreadPool 和 newSingleThreadExecutor: 主要问题是堆积的请求处理队列均采用 LinkedBlockingQueue,可能会耗费非常大的内存,甚至 OOM。
- newCachedThreadPool 和 newScheduledThreadPool: 主要问题是线程数最大数是 Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至 OOM。
3.2 向线程池提交任务
向线程池提交任务的流程非常简单,只需要向线程池的 execute 方法传入 Runnable 对象即可。
// 向线程池提交任务
threadPool.execute(new Runnable() {
@Override
public void run() {
... //待执行的任务
}
});
边栏推荐
- 秋招之路-经典面试题之手写字符串函数
- Chengdu | Changed to software testing, from zero income to over 10,000 monthly salary, a new turning point in life...
- 《STL 源码剖析》学习笔记之容器(二)list
- 滚动条样式
- FPGA设计8-3线优先编码器与3-8线译码器
- 真·摸鱼带师:程序员小哥每天工作10分钟年薪57万,我破防了...
- Chapter 02 MySQL Data Directory [1. MySQL Architecture] [MySQL Advanced]
- 如何灵活管理权限,保障团队数据安全?|2分钟了解 ONES
- The backslash \\ in MySQL is really a pit
- swin-transformer初步理解
猜你喜欢
Apifox免费吗?完全免费,不限团队人数,不限功能
AI 通过了图灵测试,科学家反应冷淡:“很棒,但没必要”
如何防止订单重复支付?
7 lines of code crashed station B for 3 hours, but because of "a tricky 0"
第02章 MySQL的数据目录【1.MySQL架构篇】【MySQL高级】
五种常见IO模型
嵌入式开发:嵌入式基础——软件错误分类
Answer these 3 interview questions correctly, and the salary will go up by 20K
低代码三部曲之未来
What should I do if the Win11 network is unstable?The solution to frequent disconnection of wifi connection in Win11
随机推荐
实现一个可调节大小的 Switch 开关
R语言时间序列数据提取:使用xts包的last函数提取时间序列中最后面10天的数据(last 10 day)
新西藏,在云上!
Working for 9 years!
项目分析(三个小众的嵌入式产品)
[数学]必备基本知识
从零在AutoDL调试一份目标检测代码
滚动条样式
Answer these 3 interview questions correctly, and the salary will go up by 20K
关于高考选志愿
centos7 server security policy
吴恩达撰文:公共数据的 “围墙”
2.1寸旋钮屏结合6.86寸串口屏助力集成灶智能升级|启明智显
Really touch the fish and lead the teacher: The programmer brother works 10 minutes a day with an annual salary of 570,000. I broke the defense...
成都 | 转行软件测试,从零收入到月薪过万,人生迎来新转折...
Security whole configuration does not take effect after the Gateway?
答对这3个面试问题,薪资直涨20K
Typescript类功能混合(mixin)使用,将多个类中功能合并到一个对象
如何防止订单重复支付?
centos8安装redis