当前位置:网站首页>多线程 @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
边栏推荐
- Force deduction brush question 101 Symmetric binary tree
- elmo(BiLSTM-CRF+elmo)(Conll-2003 命名实体识别NER)
- Quartus prime hardware experimental development (de2-115 board) experiment II function adjustable comprehensive timer design
- Wechat applet
- STM32 learning record 0007 - new project (based on register version)
- Un modèle universel pour la construction d'un modèle d'apprentissage scikit
- Reading notes: meta matrix factorization for federated rating predictions
- Three characteristics of volatile keyword [data visibility, prohibition of instruction rearrangement and no guarantee of operation atomicity]
- Jenkins construction and use
- SQL learning | complex query
猜你喜欢

2021年秋招,薪资排行NO

SSM project deployed in Alibaba cloud

1256: bouquet for algenon

SQL learning | complex query

elmo(BiLSTM-CRF+elmo)(Conll-2003 命名实体识别NER)

蓝绿发布、滚动发布、灰度发布,有什么区别?

scikit-learn構建模型的萬能模板

Small case of web login (including verification code login)

Quartus prime hardware experimental development (de2-115 board) experiment 1 CPU instruction calculator design

33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
随机推荐
Tensorflow & pytorch common error reporting
freeCodeCamp----arithmetic_ Arranger exercise
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
【项目】小帽外卖(八)
JS 烧脑面试题大赏
JS force deduction brush question 103 Zigzag sequence traversal of binary tree
Detailed explanation of redis (Basic + data type + transaction + persistence + publish and subscribe + master-slave replication + sentinel + cache penetration, breakdown and avalanche)
The latest development of fed digital currency
Solution of discarding evaluate function in surprise Library
Strange bug of cnpm
MySQL [SQL performance analysis + SQL tuning]
Three characteristics of volatile keyword [data visibility, prohibition of instruction rearrangement and no guarantee of operation atomicity]
大专的我,闭关苦学 56 天,含泪拿下阿里 offer,五轮面试,六个小时灵魂拷问
What is the difference between blue-green publishing, rolling publishing and gray publishing?
Problems encountered in the project (V) understanding of operating excel interface poi
10g database cannot be started when using large memory host
[VMware] address of VMware Tools
1256:献给阿尔吉侬的花束
Oracle告警日志alert.log和跟踪trace文件中文乱码显示
Express ② (routage)