当前位置:网站首页>多线程 @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
边栏推荐
- JMeter pressure test tool
- SSM project deployed in Alibaba cloud
- FDFS start
- Oracle告警日志alert.log和跟踪trace文件中文乱码显示
- Express②(路由)
- Reading notes: meta matrix factorization for federated rating predictions
- STM32学习记录0007——新建工程(基于寄存器版)
- leetcode--357. 统计各位数字都不同的数字个数
- UNIX final exam summary -- for direct Department
- 淘宝发布宝贝提示“您的消保保证金额度不足,已启动到期保障”
猜你喜欢
随机推荐
Pytorch 经典卷积神经网络 LeNet
Record a strange bug: component copy after cache component jump
How does redis solve the problems of cache avalanche, cache breakdown and cache penetration
Crontab timing task output generates a large number of mail and runs out of file system inode problem processing
Force deduction brush question 101 Symmetric binary tree
基于Ocelot的gRpc网关
解决方案架构师的小锦囊 - 架构图的 5 种类型
Solution of discarding evaluate function in surprise Library
L2-024 部落 (25 分)
程序编译调试学习记录
Program compilation and debugging learning record
自动化的艺术
Kettle--控件解析
SQL learning | complex query
MySQL [SQL performance analysis + SQL tuning]
VsCode-Go
STM32学习记录0007——新建工程(基于寄存器版)
Basic knowledge learning record
Yarn online dynamic resource tuning
Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed







![Special test 05 · double integral [Li Yanfang's whole class]](/img/af/0d52a6268166812425296c3aeb8f85.png)

