前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot:@Async如何自定义线程池以及使用教程

SpringBoot:@Async如何自定义线程池以及使用教程

作者头像
知识浅谈
发布2024-05-25 08:47:36
4950
发布2024-05-25 08:47:36
举报
文章被收录于专栏:分享学习

看别的教程一大堆废话,直接上干货不行吗,直接看下边例子

🎈引入依赖

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

🎈配置异步线程池

代码语言:javascript
复制
@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;
    }

}

🎈异步方法

代码语言:javascript
复制
@RestController("/test")
public class Test2Controller {
    @Async("threadPool1")
    public void test1() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("test1");
    }
}

🎈调用异步方法

代码语言:javascript
复制
@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秒后打印出来。

在这里插入图片描述
在这里插入图片描述

🍚总结

大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 🎈引入依赖
  • 🎈配置异步线程池
  • 🎈异步方法
  • 🎈调用异步方法
  • 🍚总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档