当前位置:网站首页>多线程 @Async 线程池
多线程 @Async 线程池
2022-04-23 14:00:00 【Kramer_149】
ThreadPoolExecutor
ThreadPoolExecutor是JDK自带的线程池
参考文章
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
// 省略相关代码
}
- corePoolSize
核心线程数 - maximumPoolSize
最大线程数 - keepAliveTime
最大线程数可以存活的时间,就是线程池中除了核心线程之外的其他的最长可以保留的时间,因为在线程池中,除了核心线程即使在无任务的情况下也不能被清除,其余的都是有存活时间的,意思就是非核心线程可以保留的最长的空闲时间 - unit
计算keepAliveTime的单位 - workQueue
阻塞(等待)队列。一共有ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue等7种阻塞队列 - threadFactory
创建线程的工厂,主要用来创建线程,默认为正常优先级、非守护线程。 - handler
拒绝策略。一共有下面四种: -
- AbortPolicy
不执行新任务,直接抛出异常,提示线程池已满
- AbortPolicy
-
- DisCardPolicy
不执行新任务,也不抛出异常
- DisCardPolicy
-
- DisCardOldSetPolicy
将消息队列中的第一个任务替换为当前新进来的任务执行
- DisCardOldSetPolicy
-
- CallerRunsPolicy
直接调用execute来执行当前任务
- CallerRunsPolicy
示例:
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(3,5,1L, TimeUnit.SECONDS,new ArrayBlockingQueue(4),Executors.defaultThreadFactory());
for(int i=0;i<7;i++){
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+" "+"--->办理业务");
});
}
executorService.shutdown();
}
}
Spring ThreadPoolTaskExecutor
示例
在异步方法上添加@Async注解,然后还需要在@SpringBootApplication启动类或者@Configuration注解类上 添加注解@EnableAsync启动多线程注解,@Async就会对标注的方法开启异步多线程调用,注意,这个方法的类一定要交给Spring容器来管理
配置文件application.properties
# 核心线程池数
spring.task.execution.pool.core-size=5
# 最大线程池数
spring.task.execution.pool.max-size=10
# 任务队列的容量
spring.task.execution.pool.queue-capacity=5
# 非核心线程的存活时间
spring.task.execution.pool.keep-alive=60
# 线程池的前缀名称
spring.task.execution.thread-name-prefix=god-jiang-task-
配置类AsyncScheduledTaskConfig.java
@Configuration
public class AsyncScheduledTaskConfig {
@Value("${spring.task.execution.pool.core-size}")
private int corePoolSize;
@Value("${spring.task.execution.pool.max-size}")
private int maxPoolSize;
@Value("${spring.task.execution.pool.queue-capacity}")
private int queueCapacity;
@Value("${spring.task.execution.thread-name-prefix}")
private String namePrefix;
@Value("${spring.task.execution.pool.keep-alive}")
private int keepAliveSeconds;
@Bean
public Executor myAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//最大线程数
executor.setMaxPoolSize(maxPoolSize);
//核心线程数
executor.setCorePoolSize(corePoolSize);
//任务队列的大小
executor.setQueueCapacity(queueCapacity);
//线程前缀名
executor.setThreadNamePrefix(namePrefix);
//线程存活时间
executor.setKeepAliveSeconds(keepAliveSeconds);
/** * 拒绝处理策略 * CallerRunsPolicy():交由调用方线程运行,比如 main 线程。 * AbortPolicy():直接抛出异常。 * DiscardPolicy():直接丢弃。 * DiscardOldestPolicy():丢弃队列中最老的任务。 */
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//线程初始化
executor.initialize();
return executor;
}
}
服务类
@Component
@EnableAsync
public class ScheduleTask {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Async("myAsync")
@Scheduled(fixedRate = 2000)
public void testScheduleTask() {
try {
Thread.sleep(6000);
System.out.println("Spring1自带的线程池" + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async("myAsync")
@Scheduled(cron = "*/2 * * * * ?")
public void testAsyn() {
try {
Thread.sleep(1000);
System.out.println("Spring2自带的线程池" + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
版权声明
本文为[Kramer_149]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_46199937/article/details/122813024
边栏推荐
- 商家案例 | 运动健康APP用户促活怎么做?做好这几点足矣
- 低频量化之明日涨停预测
- Analysis of unused index columns caused by implicit conversion of timestamp
- Technologie zéro copie
- 2022年江西最新建筑八大员(质量员)模拟考试题库及答案解析
- AttributeError: ‘dict‘ object has no attribute ‘iteritems‘
- JS 力扣刷题 103. 二叉树的锯齿形层序遍历
- Analysis and understanding of atomicintegerarray source code
- STM32 learning record 0007 - new project (based on register version)
- Analysis of redo log generated by select command
猜你喜欢
Question bank and answer analysis of the 2022 simulated examination of the latest eight members of Jiangxi construction (quality control)
STM32 learning record 0007 - new project (based on register version)
3300万IOPS、39微秒延迟、碳足迹认证,谁在认真搞事情?
Choreographer全解析
Android 面试主题集合整理
程序编译调试学习记录
Detailed explanation of redis (Basic + data type + transaction + persistence + publish and subscribe + master-slave replication + sentinel + cache penetration, breakdown and avalanche)
Oracle alarm log alert Chinese trace and trace files
基础知识学习记录
Wechat applet
随机推荐
变长参数__VA_ARGS__ 和 写日志的宏定义
Leetcode? The first common node of two linked lists
初探 Lambda Powertools TypeScript
What is the difference between blue-green publishing, rolling publishing and gray publishing?
【项目】小帽外卖(八)
MySQL index [data structure + index creation principle]
Crontab timing task output generates a large number of mail and runs out of file system inode problem processing
Jiannanchun understood the word game
About note 1
Express中间件③(自定义中间件)
The latest development of fed digital currency
JS 烧脑面试题大赏
Leetcode | 38 appearance array
Express middleware ③ (custom Middleware)
[code analysis (5)] communication efficient learning of deep networks from decentralized data
scikit-learn構建模型的萬能模板
Multithreading
Express②(路由)
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
村上春树 --《当我谈跑步时,我谈些什么》句子摘录