当前位置:网站首页>多线程 @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
边栏推荐
- VsCode-Go
- 初探 Lambda Powertools TypeScript
- leetcode--357. 统计各位数字都不同的数字个数
- [code analysis (5)] communication efficient learning of deep networks from decentralized data
- Multithreading
- Pytorch 经典卷积神经网络 LeNet
- Basic SQL query and learning
- OSS cloud storage management practice (polite experience)
- Android interview theme collection
- JS force deduction brush question 103 Zigzag sequence traversal of binary tree
猜你喜欢
随机推荐
China creates vast research infrastructure to support ambitious climate goals
Express ② (routing)
2022年江西最新建筑八大员(质量员)模拟考试题库及答案解析
Tensorflow & pytorch common error reporting
VsCode-Go
1256: bouquet for algenon
Express middleware ③ (custom Middleware)
初识go语言
读了一篇博客,重新理解闭包整理一下
趣谈网络协议
Dynamic subset division problem
JS 力扣刷题 102. 二叉树的层序遍历
Analysis of redo log generated by select command
Problems encountered in the project (V) understanding of operating excel interface poi
快捷键(多行)
Special test 05 · double integral [Li Yanfang's whole class]
Building MySQL environment under Ubuntu & getting to know SQL
The art of automation
JUC interview questions about synchronized, ThreadLocal, thread pool and atomic atomic classes
Haruki Murakami -- Excerpt from "what do I talk about when I talk about running"