SpringBoot @Async如何自定义线程池及使用教程
更新时间:2024年01月22日 15:08:31 作者:知识浅谈
这篇文章主要介绍了SpringBoot @Async如何自定义线程池及使用教程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
看别的教程一大堆废话,直接上干货不行吗,直接看下边例子
🎈配置异步线程池
@EnableAsync
@Configuration
public class AsyncConfiguration {
//定义线程池
@Bean("threadPool1") // bean的名称,线程池的bean的名字,不是创建线程的名字
public Executor ThreadPool1(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); /** 核心线程数(默认线程数) */
executor.setMaxPoolSize(20);/** 最大线程数 */
executor.setQueueCapacity(500);/** 缓冲队列大小 */
executor.setKeepAliveSeconds(60);/** 允许线程空闲时间(单位:默认为秒) */
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("task-thread-"); /** 线程池名前缀 */
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); //拒绝策略:缓存队列满了之后由调用线程处理,一般是主线程
executor.initialize();
return executor;
}
}🎈异步方法
@RestController("/test")
public class Test2Controller {
@Async("threadPool1")
public void test1() throws InterruptedException {
Thread.sleep(5000);
System.out.println("test1");
}
}🎈调用异步方法
@Api("测试")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController
{
@Autowired
private Test2Controller test2Controller;
@ApiOperation("异步")
@GetMapping("/testAsync")
public String testAsync() throws InterruptedException {
test2Controller.test1();
return "async";
}
}结果:
结果直接返回:test1 5秒后打印出来。

🍚总结
到此这篇关于SpringBoot @Async如何自定义线程池以及使用教程的文章就介绍到这了,更多相关SpringBoot @Async自定义线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
一篇文章带你了解jdk1.8新特性--为什么使用lambda表达式
Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码,本篇文章就带你了解,希望能给你带来帮助2021-08-08
Spring Cloud升级最新Finchley版本的所有坑
这篇文章主要介绍了Spring Cloud升级最新Finchley版本的所有坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-08-08
Spring Boot 2.4 对多环境配置的支持更改示例代码
这篇文章主要介绍了Spring Boot 2.4 对多环境配置的支持更改,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-12-12


最新评论