当前位置:网站首页>线程池的七个参数与拒绝策略
线程池的七个参数与拒绝策略
2022-06-11 14:08:00 【金清泽】
线程池
概述
为什么需要使用线程池?
回顾我们之前已经认识的数据库连接池,不使用数据库连接池的时候,每次使用完连接对象都需要销毁,下次使用又需要创建,这样很消耗时间。
使用数据库连接池后,会事先创建出一些连接对象,放在池子中,需要的时候从连接池中取出,用完了放回池子里。
线程池也大概是这样的,如果线程数量很多,频发的创建和销毁线程会耗费大量的时间。在jdk5之前是手动实现线程池,jdk5之后,java内置支持线程池。
jdk5增加了 ThreadPoolExecutor实现线程池,同时使用Executors创建不同类型的线程池:
newSingleThreadExecutor:创建一个单线程线程池,因为异常结束会重新创建一个新的。
newFixedThreadPool:创建固定大小的线程池。根据提交的任务逐个增加线程,指导最大值保持不变。如果因异常结束,会新创建一个线程补充。
newCachedThreadPool:创建一个可缓存的线程池。会根据任务自动新增或回收线程。
但是一般不提供Executors类来创建。
线程池优点:
重复利用线程,降低线程创建和销毁带来的资源消耗。
统一管理线程,线程的创建和销毁都由线程池进行管理。
提高响应速度,线程创建已经完成,任务来到可直接处理,省去了创建时间。
ThreadPoolExecutor类
提供了四个构造方法,但是其余三个构造方法最后都调用7个参数的构造方法。
7个参数的含义
corePoolSize:核心线程池大小,创建对象后,池中默认是没有线程的,当有任务到达后才会创建线程执行,执行完后,线程就不销毁了。知道创建出于核心池子大小相等数量的线程。
除非使用了prestartAllCoreThreads()或者prestartCoreThread()方法,线程池在任务没到来之前就会创建一个线程。
maximumPoolSize:下次你恒驰最大线程出,表示线程池中对多能创建多少个线程。
keepAliveTime:表示线程没有任务执行后多久会进行销毁。默认情况下只有当线程数量大于核心池子时,才会起作用,直到线程池中的线程数量不超过corePoolSize。
unit:参数KeepAliveTime的时间单位,有7中取值,在TimeUnit类中有 7中静态属性(天、小时、分钟、秒、毫秒、微妙、纳秒)
workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择很重要,会对线程池的运行过程产生重大影响。
threadFactory:创建工厂用来创建线程。
handler:表示线程池的拒绝策略,有四种。
线程池的执行
创建完毕线程池后,每次提交任务时,会使用execute 方法,流程图如下:

- 如果线程池中的线程数量小于核心池中的数量时,会创建线程到核心池中执行任务。
- 如果线程池中的线程数量大于核心池中的数量时,会判断队列是否已经满了,如果没满就将任务加入到队列中。
- 如果队列中的线程数量也已经满了,判断线程数量是否大于线程的最大数量,如果小于最大数量,会创建非核心线程执行任务。
- 如果线程数量大于最大数量,会执行执行策略。
线程池中的队列
SynchronousQueue:同步队列式一个容量只有1的队列,不会保存提交任务,只是新建一个线程来执行新来的任务。
ArrayBlockingQueue:有界队列,是一个用数组实现的有界阻塞队列,按FIFO排序量。
LinkedBlockingQueue:可设置容量队列,基于链表的阻塞队列,按FIFO排序任务,容量可以进行设置,不设置的话就是一个无边界的阻塞队列,最大长度为Integer.MAX_VALUE.
线程池的拒绝策略
线程池提供了四种类型的拒绝策略
- AbortPolicy策略,会直接抛出异常
- CallerRunsPolicy策略,只要线程池未关闭,该策略在调用线程中运行当前任务(如果任务被拒绝了,则由提交任务的线程(例如main)直接执行此任务)
- DiscardOledestPolicy策略,丢弃最老的请求,尝试再次提交当前任务。
- DiscardPolicy策略,丢弃无法处理的任务,不予任何处理。
/* 任务 */
public class MyTask implements Runnable {
private int taskNum;
public MyTask(int num) {
this.taskNum = num;
}
@Override
public void run() {
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":task "+taskNum+"执行完毕");
}
}
/* 在测试类中修改拒绝策略查看特性和区别 */
public class Test {
public static void main(String[] args) {
//创建线程池 7
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
5, 200,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(2),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
for(int i=1;i<=20;i++){
MyTask myTask = new MyTask(i);
executor.execute(myTask);//添加任务到线程池
//Future<?> submit = executor.submit(myTask);
}
executor.shutdown();
}
}
execute 与 submit 的区别
执行任务除了可以使用execute方法还可以使用submit方法。
execute适用于不需要关注返回值的场景
submit方法适用于需要关注返回值的场景
关闭线程池
关闭线程池可以调用 shutdownNow 和 shutdown 两个方法来实现。
shutdownNow:对正在执行的线程发出interrupt(),停止执行,未开始执行的任务也全部取消,返回还没开始的任务列表。
shutdown:线程池不再接受新的任务,单页不会强制终止已经提交或者正在执行中的任务。
边栏推荐
- Ali talked about the use of strategic mode in the project
- Chip engineers are too expensive? Your sister
- Current situation and future development trend of metal organic chemical vapor deposition (MOCVD) market in the world and China from 2022 to 2028
- 【公开课预告】:MXPlayer OTT音视频转码实践和优化
- CVPR 2022 | 神经辐射场几何编辑方法NeRF-Editing
- [pyhton crawler] regular expression
- Xiaomi 9-wire brush ROM
- tp6基于whoops的异常接管(漂亮的界面)
- Question bank and answers for 2022 tool fitter (intermediate) operation certificate examination
- Hamad application scheduling scheme 06 of hashicopy (configure task)
猜你喜欢

Lake Shore HR series sensors

【Try to Hack】URL

Code comparison tool, I use these six

Leetcode 1968. 构造元素不等于两相邻元素平均值的数组(可以,终于解决)

Vi LXD deployment of lab server for development records

cadence SPB17.4 - group operation(add to group, view group list, delete group)

非常值得学习的调度开源库推荐

Leetcode 1968. Construct an array whose elements are not equal to the average value of two adjacent elements (yes, finally solved)

Easyexcel configuration and Application

CVPR 2022 | neural radiation field geometry editing method nerf editing
随机推荐
In depth research and analysis report on global and Chinese sanitary safety product market
Pond (topology + priority queue)
Is bone conduction earphone good for bone? Is bone conduction earphone harmful to the body?
Introduction to reverse learning - excellent assembly debugging tool OllyDbg
Three level classification display
非常值得学习的调度开源库推荐
Implementation of VGA protocol based on FPGA
[public class preview]: mxplayer Ott audio and video transcoding practice and optimization
非常值得學習的調度開源庫推薦
[issue 268] accidentally submit the test code to the production environment. I will teach you six ways to solve it in seconds!
2022-2028 near infrared (NIR) analyzer Market Status and future development trend in the world and China
使用cpolar远程办公(1)
Easyexcel configuration and Application
mysql高级语句
二十八-三维点云实时和离线生成二维栅格、三维栅格地图
In depth research and analysis report on ready to eat meat market for vacuum low temperature cooking in the world and China
2022年甘肃省安全员B证考试题模拟考试题库及在线模拟考试
优化调度(火电、风、储能)(Matlab实现)
Leetcode 1968. Construct an array whose elements are not equal to the average value of two adjacent elements (yes, finally solved)
Telecommuting with cpolar (1)