当前位置:网站首页>四大线程池简析
四大线程池简析
2022-07-27 12:50:00 【炸了毛的猫】
四大线程池简析
文章目录
1、FixedThreadPool
1.1、参数简析
定长线程池,首先先看一下创建的构造方法参数。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
特点:
- 核心线程数量与非核心线程数量相等,所以只存在核心线程,不存在非核心线程。
- 如果不主动设置,核心线程的生命周期与线程池相同。
- 采用的无界阻塞队列
LinkedBlockingQueue。
1.2、使用场景
因为只存在核心线程,并且线程最大长度固定,所以适用于:
- 任务的个数比较固定
- 流程较长
2、ScheduledThreadPool
2.1、参数简析
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
特点:
- 核心线程数量为
corePoolSize,非核心线程数量无限大。 - 如果不主动设置,核心线程的生命周期与线程池相同 ;,若队列中无任务非核心线程将立刻被回收。
- 采用的延迟队列
DelayedWorkQueue。
2.2、应用场景
适用于执行定时任务和具体固定周期的重复任务
3、CachedThreadPool
3.1、参数简析
缓冲线程池。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
特点:
- 只存在非核心线程,核心线程为0,非核心线程无限大。
- 非核心线程空闲时间为
60s,超过60s将会被回收。 - 采用的同步阻塞队列
SynchronousQueue,该队列特点长度为1 ,只有当存在空闲线程的时候才会入队,否则直接创建新的非核心线程执行任务。
3.2、应用场景
适用于任务多,流程时间较短的任务。
4、SingleThreadExecutor
4.1、参数简析
单例线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
特点:
- 核心线程与非核心线程数量都为1.
- 线程生命周期与线程池相同。
- 采用的无界阻塞队列LinkedBlockingQueue
4.2、适用场景
适用于 任务顺序执行的场景。
5、队列选择
在执行进入队列之前,先熟悉一下线程池的执行流程:
如果工作线程的数量少于corePoolSize(核心线程)的数量,此时任务是不会入队的,而是直接创建新的线程执行该任务,然后去队列中获取新的任务来执行。
如果工作线程的数量大于等于了corePoolSize此时是会进行入队操作的,后续是否创建线程根据maximumPoolSize(最大线程)以及是否存在工作线程来定。
5.1、无界队列
无界队列特点就是队列大小无限制(Integer.MAX_VALUE),常用的无界队列为LinkedBlockingQueue。上述的SingleThreadExecutor、FixedThreadPool两个线程池就是采用的该阻塞队列。使用该队列时,注意以为队列大小无限制,避免存放过多的数据导致内存溢出。
5.2、有界队列
与无界队列相对应,队列大小有限制,常用的有两类,一类是遵循FIFO原则的队列如ArrayBlockingQueue,另一类是优先级队列如PriorityBlockingQueue。PriorityBlockingQueue中的优先级由任务的Comparator决定。
使用有界队列时队列大小需和线程池大小互相配合,线程池较小有界队列较大时可减少内存消耗,降低cpu使用率和上下文切换,但是可能会限制系统吞吐量。
5.3、同步移交队列
该队列在线程池的使用是,任务无需等待,存在空闲线程任务才会入队,否则直接创建新的线程,对应的就是CachedThreadPool线程池。所以使用该队列可能会创建大量的线程,应注意使用。
6、拒绝策略
6.1、AbortPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
直接抛出异常策略,使用者可以直接捕获该异常,在做进一步处理,比如可以再次将任务加入到线程池中去,或者直接放弃。
6.2、CallerRunsPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
可以看出该策略,既没有抛出异常,也没有放弃,而是直接调用了run方法,而不是在线程池中进行调用,所以该策略会阻塞主线程的执行,让主线程执行该任务。
6.3、DiscardPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
什么也不做,直接放弃该任务。
6.4、DiscardOldestPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
1、在队列中出队一个任务。
e.getQueue().poll();
e.execute(r);
}
}
如代码,先将阻塞队列中的头元素出队抛弃,再尝试提交任务。如果此时阻塞队列使用PriorityBlockingQueue优先级队列,将会导致优先级最高的任务被抛弃,因此不建议将该种策略配合优先级队列使用。
边栏推荐
- 完美指南|如何使用 ODBC 进行无代理 Oracle 数据库监控?
- 附加:【URLEncoder.encode(待编码字符串, “编码方式“);】(是什么?;我们向cookie中设置值的时候,为什么要使用这个去编码?)(待完善……)
- 初探基于OSG+OCC的CAD之任意多个子模型进行netgen以及gmsh网格划分
- [nuxt 3] (XII) project directory structure 2
- Initializing database error after reinstalling MySQL
- 字节跳动的 Flink OLAP 作业调度和查询执行优化实践
- clear
- 51:第五章:开发admin管理服务:4:开发【新增admin账号,接口】;(只开发了【用户名+密码的,方式】;【@T…】注解控制事务;设置cookie时,是否需要使用URLEncoder去编码;)
- C语言犄角旮旯的知识之数组与函数
- 500强企业如何提升研发效能?来看看行业专家怎么说!
猜你喜欢

51:第五章:开发admin管理服务:4:开发【新增admin账号,接口】;(只开发了【用户名+密码的,方式】;【@T…】注解控制事务;设置cookie时,是否需要使用URLEncoder去编码;)

Redis summary: cache avalanche, cache breakdown, cache penetration and cache preheating, cache degradation

A survey of video game addictive behavior research

程序员培训学习后好找工作吗

W3School导航栏练习

Getting started for beginners: build your own blog with WordPress

Multi activity disaster recovery construction after 713 failure of station B | takintalks share

MTK6765编译环境搭建

Optimization Practice of Flink OLAP job scheduling and query execution based on ByteDance

Qt优秀开源项目之十三:QScintilla
随机推荐
[node+ts] build node+typescript project
Feign的两个调用处理器
leetcode——83,24;机器学习——神经网络
Mongodb slow query and index
开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能
Application of responsibility chain model in transfer accurate valuation
Optimization Practice of Flink OLAP job scheduling and query execution based on ByteDance
Zhongke Lanxun fell 30% on the first day of listing: Huang Zhiqiang, 60, started a company with a market value of 7.7 billion
Will saffron become a safe and effective natural therapy for patients with arthritis?
Insert sort, positive order, reverse order
Pyside6/pyqt development experience summary (2) - set shortcut keys
51:第五章:开发admin管理服务:4:开发【新增admin账号,接口】;(只开发了【用户名+密码的,方式】;【@T…】注解控制事务;设置cookie时,是否需要使用URLEncoder去编码;)
592. Fraction addition and subtraction: introduction to expression calculation
Getting started for beginners: build your own blog with WordPress
面试考点:三种图的问题
2022年7月24日 暑假第二周训练
Fixed positioning
初探基于OSG+OCC的CAD之任意多个子模型进行netgen以及gmsh网格划分
500强企业如何提升研发效能?来看看行业专家怎么说!
Gan: generate adversarial networks