1.實(shí)現(xiàn)原理
Spring 通過任務(wù)執(zhí)行器(TaskExecutor)來實(shí)現(xiàn)多線程和并發(fā)編程
使用ThreadPoolTaskExecutor實(shí)現(xiàn)一個(gè)基于線程池的TaskExecutor
2.使用步驟
2.1 配置類
2.1.1使用@EnableAsync開啟異步任務(wù)支持;
2.1.2配置類需要實(shí)現(xiàn)AsyncConfigure接口并重寫getAsyncExecutor和getAsyncUncaughtExceptionHandler方法
2.2 任務(wù)執(zhí)行類
通過@Async注解表明這個(gè)方法是一個(gè)異步方法
3.demo
3.1配置類
@Configuration
@ComponentScan("com.xxx.springboot.springbootdemo")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return null;
}
}
3.2任務(wù)執(zhí)行類
@Service
public class AsyncTaskService {
@Async
public void executeAsyncTask1(Integer i){
System.out.println(Thread.currentThread().getName()+"執(zhí)行異步任務(wù)1:"+i);
}
@Async
public void executeAsyncTask2(Integer i){
System.out.println(Thread.currentThread().getName()+"執(zhí)行異步任務(wù)2:"+i);
}
}
3.3 執(zhí)行
public static void main(String[] args) {
AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
for(int i=0;i<10;i++){
asyncTaskService.executeAsyncTask1(i);
asyncTaskService.executeAsyncTask2(i);
}
context.close();
}
3.4執(zhí)行結(jié)果

4.設(shè)置參數(shù)
Spring 中的ThreadPoolExecutor是借助JDK并發(fā)包中的java.util.concurrent.ThreadPoolExecutor來實(shí)現(xiàn)的。其中一些值的含義如下:
int corePoolSize:線程池維護(hù)線程的最小數(shù)量
int maximumPoolSize:線程池維護(hù)線程的最大數(shù)量,線程池中允許的最大線程數(shù),線程池中的當(dāng)前線程數(shù)目不會(huì)超過該值。如果隊(duì)列中任務(wù)已滿,并且當(dāng)前線程個(gè)數(shù)小于maximumPoolSize,那么會(huì)創(chuàng)建新的線程來執(zhí)行任務(wù)。
long keepAliveTime:空閑線程的存活時(shí)間TimeUnit unit:時(shí)間單位,現(xiàn)由納秒,微秒,毫秒,秒
BlockingQueue workQueue:持有等待執(zhí)行的任務(wù)隊(duì)列
RejectedExecutionHandler handler 線程池的拒絕策略,是指當(dāng)任務(wù)添加到線程池中被拒絕,而采取的處理措施。
當(dāng)任務(wù)添加到線程池中之所以被拒絕,可能是由于:第一,線程池異常關(guān)閉。第二,任務(wù)數(shù)量超過線程池的最大限制。
Reject策略預(yù)定義有四種:
(1)ThreadPoolExecutor.AbortPolicy策略,是默認(rèn)的策略,處理程序遭到拒絕將拋出運(yùn)行時(shí) RejectedExecutionException。
(2)ThreadPoolExecutor.CallerRunsPolicy策略 ,調(diào)用者的線程會(huì)執(zhí)行該任務(wù),如果執(zhí)行器已關(guān)閉,則丟棄.
(3)ThreadPoolExecutor.DiscardPolicy策略,不能執(zhí)行的任務(wù)將被丟棄.
(4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果執(zhí)行程序尚未關(guān)閉,則位于工作隊(duì)列頭部的任務(wù)將被刪除,然后重試執(zhí)行程序(如果再次失敗,則重復(fù)此過程).
【參考】
《JavaEE開發(fā)的顛覆者 SpringBoot實(shí)戰(zhàn)》