某些情況下,我們需要在項目中對多種任務分配不同的線程池進行執行。從而通過監控不同的線程池來控制不同的任務。為了達到這個目的,需要在項目中配置多線程池。
spring boot 提供了簡單高效的線程池配置和使用方案。
配置
首先是配置線程池的bean交給spring 管理:
@Configurationpublic class TaskExecutePool { @Bean(name ="threadPoolA")public ThreadPoolTaskExecutormyTaskAsyncPool() {ThreadPoolTaskExecutor executor =new ThreadPoolTaskExecutor(); executor.setCorePoolSize(4); executor.setMaxPoolSize(8); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("Pool-A"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; }@Bean(name ="ThreadPoolB")public ThreadPoolTaskExecutorAsyncPoolB() {ThreadPoolTaskExecutor executor =new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(4); executor.setQueueCapacity(8); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("Pool-B"); //當任務數量超過MaxPoolSize和QueueCapacity時使用的策略,該策略是又調用任務的線程執行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; }}
使用
使用線程只需要在執行方法上加上注釋,同時該方法的類必須被定義為bean,交由spring管理。
可以在類上使用注解@Component、@Service等
@Async(value="ThreadPoolA")public void taskA(){ ...}
查看線程活躍數:
@Autowired private ThreadPoolTaskExecutor threadPoolA;//變量名稱為定義的線程池bean定義的name屬性名。public void checkAvtiveThreadNum() { int num = threadPoolA.getActiveCount();}
當然還有其他一些方法,這里不再舉例。
線程池各屬性理解:
corePoolSize:表示線程池核心線程,正常情況下開啟的線程數量。
queueCapacity:當核心線程都在跑任務,還有多余的任務會存到此處。
maxPoolSize:如果queueCapacity存滿了,還有任務就會啟動更多的線程,直到線程數達到maxPoolSize。如果還有任務,則根據拒絕策略進行處理。
拒絕策略有多種:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選