SpringBoot @Async如何自定義線程池及使用教程
更新時間:2024年01月22日 15:08:31 作者:知識淺談
這篇文章主要介紹了SpringBoot @Async如何自定義線程池及使用教程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
看別的教程一大堆廢話,直接上干貨不行嗎,直接看下邊例子
??配置異步線程池
@EnableAsync @Configuration public class AsyncConfiguration { //定義線程池 @Bean("threadPool1") // bean的名稱,線程池的bean的名字,不是創(chuàng)建線程的名字 public Executor ThreadPool1(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); /** 核心線程數(shù)(默認線程數(shù)) */ executor.setMaxPoolSize(20);/** 最大線程數(shù) */ executor.setQueueCapacity(500);/** 緩沖隊列大小 */ executor.setKeepAliveSeconds(60);/** 允許線程空閑時間(單位:默認為秒) */ executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("task-thread-"); /** 線程池名前綴 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); //拒絕策略:緩存隊列滿了之后由調(diào)用線程處理,一般是主線程 executor.initialize(); return executor; } }
??異步方法
@RestController("/test") public class Test2Controller { @Async("threadPool1") public void test1() throws InterruptedException { Thread.sleep(5000); System.out.println("test1"); } }
??調(diào)用異步方法
@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"; } }
結(jié)果:
結(jié)果直接返回:test1 5秒后打印出來。
??總結(jié)
到此這篇關(guān)于SpringBoot @Async如何自定義線程池以及使用教程的文章就介紹到這了,更多相關(guān)SpringBoot @Async自定義線程池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一篇文章帶你了解jdk1.8新特性--為什么使用lambda表達式
Lambda是一個匿名函數(shù),我們可以把Lambda表達式理解為是一段可以傳遞的代碼,本篇文章就帶你了解,希望能給你帶來幫助2021-08-08Spring Cloud升級最新Finchley版本的所有坑
這篇文章主要介紹了Spring Cloud升級最新Finchley版本的所有坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08Spring Boot 2.4 對多環(huán)境配置的支持更改示例代碼
這篇文章主要介紹了Spring Boot 2.4 對多環(huán)境配置的支持更改,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12淺談java中math類中三種取整函數(shù)的區(qū)別
下面小編就為大家?guī)硪黄獪\談java中math類中三種取整函數(shù)的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11