SpringBoot @Async如何自定义线程池及使用教程
作者:知识浅谈
这篇文章主要介绍了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自定义线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
