一、單純使用@Async注解。
1、@Async
注解在使用時,如果不指定線程池的名稱,則使用Spring
默認的線程池,Spring
默認的線程池為SimpleAsyncTaskExecutor。
2、
方法上一旦標記了這個@Async
注解,當其它線程調用這個方法時,就會開啟一個新的子線程去異步處理該業務邏輯。
Spring
默認的線程池配置為:
核心線程數 (corePoolSize): 8
最大線程數 (maxPoolSize): Integer.MAX_VALUE (無限制)
任務等待隊列容量 (queueCapacity): Integer.MAX_VALUE (無限制)
空閑線程等待時間?(keepAliveSeconds): 60秒(超過這個時間沒有任務調度,則線程會被回收)
線程池拒絕策略 (RejectedExecutionHandler): AbortPolicy(默認策略,超出線程池容量和隊列容量時拋出RejectedExecutionException異常)
缺點
:并發情況下,會無限創建線程。自定義配置參數可以解決該問題。
在配置文件中配置即可:
spirng:task:execution:# 線程名稱前綴thread-name-prefix:pool:# 最大線程數,默認為Integer.MAX_VALUEmax-size:# 核心線程數,默認為8core-size:# 空閑線程等待時間,默認為60s。如果超過這個時間沒有任務調度,則線程會被回收keep-alive:# 任務等待隊列容量,默認為Integer.MAX_VALUE 無限制queue-capacity:# 是否允許回收空閑的線程,默認為trueallow-core-thread-timeout:
二、如果需要更加精確地控制線程池的參數,您也可以在配置類中自定義一個?ThreadPoolTaskExecutor
?bean,并根據具體需求設置相應的參數。
配置類如下:
@Configuration
public class ThreadPoolConfig {@Bean("myExecutor")public Executor taskExecutor() {ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();//設置線程池參數信息taskExecutor.setCorePoolSize(10);taskExecutor.setMaxPoolSize(50);taskExecutor.setQueueCapacity(200);taskExecutor.setKeepAliveSeconds(60);taskExecutor.setThreadNamePrefix("myExecutor--");taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//線程池中任務等待時間,超過等待時間直接銷毀taskExecutor.setAwaitTerminationSeconds(60);//修改拒絕策略為使用當前線程執行taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//初始化線程池taskExecutor.initialize();return taskExecutor;}
}
可配合@Async注解使用:
@Async("myExecutor")
public void hello(String name){logger.info("異步線程啟動 started."+name);
}