哈嘍,大家好,我是了不起。
我們在日常開發中,經常跟多線程打交道,Spring 為我們提供了一個線程池方便我們開發,它就是 ThreadPoolTaskExecutor ,接下來我們就來聊聊 Spring 的線程池吧。
SpringBoot 提供了注解 @Async 來使用線程池, 具體使用方法如下:
下面是一個簡單的例子:
@Component@EnableAsync@EnableSchedulingpublic class ScheduleTask { @Async @Scheduled(fixedRate = 2000) public void testAsync1() { try { Thread.sleep(6000); System.out.println(LocalDateTime.now() + "--線程1:" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } @Async @Scheduled(cron = "*/2 * * * * ?") public void testAsync2() { try { Thread.sleep(1000); System.out.println(LocalDateTime.now() + "--線程2:" + Thread.currentThread().getName()); } catch (Exception ex) { ex.printStackTrace(); } }}
啟動項目,得到如下日志結果:
圖片
可以發現在當前環境下 task-${id} 這個 id 并不是一直增長的,而是一直在復用 1-8。這個時候可能就會有的小伙伴們會比較好奇,默認的不是 SimpleAsyncTaskExecutor 嗎?為什么從日志打印的效果上看像是一直在復用 8 個線程,難道用的是 ThreadPoolTaskExecutor?
原因是 SpringBoot2.1.0 版本后,新增了 TaskExecutionAutoConfiguration 配置類。其中聲明的默認線程池就是 ThreadPoolTaskExecutor 。而 @Async 在選擇執行器的時候會先去 IOC 容器中先找是否有 TaskExecutor 的 Bean對象,所以在當前版本 SpringBoot 中,@Async 的默認 TaskExecutor 是 ThreadPoolTaskExecutor。
在 SpringBoot 項目中,我們可以在 yaml 或者 properties 配置文件中配置,或者使用 @Configuration 配置,下面演示配置方法。
# 核心線程池數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=test-task-
@Bean(name = "myThreadPoolTaskExecutor")public ThreadPoolTaskExecutor getMyThreadPoolTaskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); int i = Runtime.getRuntime().availableProcessors(); taskExecutor.setCorePoolSize(i * 2); taskExecutor.setMaxPoolSize(i * 2); taskExecutor.setQueueCapacity(i * 2 * 100); taskExecutor.setKeepAliveSeconds(60); taskExecutor.setThreadNamePrefix("my-task-"); taskExecutor.initialize(); return taskExecutor;}
RejectedExectutionHandler 參數字段用于配置絕策略,常用拒絕策略如下
上面簡單介紹了 Spring 自帶的線程池 ThreadPoolTaskExecutor 的配置和使用,并且講了線程池的參數和處理流程。當然Spring提供了7個線程池的實現,感興趣的可以自行了解~
本文鏈接:http://www.tebozhan.com/showinfo-26-13250-0.html解密SpringBoot線程池
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com