0608142600.png
1.自定義線程池
@EnableAsync
@Configuration
public class BeanConfig {
@Bean("taskExecutor")
public Executor initTaskExecutor(){
ThreadPoolTaskExecutor executor= new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
上面我們通過使用 ThreadPoolTaskExecutor創(chuàng)建了一個(gè)線程池,同時(shí)設(shè)置了以下這些參數(shù):
?核心線程數(shù)10:線程池創(chuàng)建時(shí)候初始化的線程數(shù)
?最大線程數(shù)20:線程池最大的線程數(shù),只有在緩沖隊(duì)列滿了之后才會(huì)申請(qǐng)超過核心線程數(shù)的線程
?緩沖隊(duì)列200:用來緩沖執(zhí)行任務(wù)的隊(duì)列
?允許線程的空閑時(shí)間60秒:當(dāng)超過了核心線程出之外的線程在空閑時(shí)間到達(dá)之后會(huì)被銷毀
?線程池名的前綴:設(shè)置好了之后可以方便我們定位處理任務(wù)所在的線程池
?線程池對(duì)拒絕任務(wù)的處理策略:這里采用了 CallerRunsPolicy策略,當(dāng)線程池沒有處理能力的時(shí)候,該策略會(huì)直接在 execute 方法的調(diào)用線程中運(yùn)行被拒絕的任務(wù);如果執(zhí)行程序已關(guān)閉,則會(huì)丟棄該任務(wù)
2.定義任務(wù)執(zhí)行類ExecutorTaskService
@Service
public class ExecutorTaskService {
@Async("taskExecutor")
public void doTask1() throws InterruptedException {
System.out.println("開始做任務(wù)一");
long start = System.currentTimeMillis();
Thread.sleep(2000);
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)一,耗時(shí):" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTask2() throws InterruptedException {
System.out.println("開始做任務(wù)二");
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)二,耗時(shí):" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTask3() throws InterruptedException {
System.out.println("開始做任務(wù)三");
long start = System.currentTimeMillis();
Thread.sleep(500);
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)三,耗時(shí):" + (end - start) + "毫秒");
}
}
3.定義controller
@RequestMapping("/executor")
@Controller
public class ExecutorTaskCtrl {
@Autowired
private ExecutorTaskService executorTaskService;
@RequestMapping(value = "/doTask",method = RequestMethod.GET)
@ResponseBody
public void doTask() throws InterruptedException {
executorTaskService.doTask1();
executorTaskService.doTask2();
executorTaskService.doTask3();
}
}
訪問http://localhost:9999/executor/doTask 查看打印結(jié)果:
開始做任務(wù)二
開始做任務(wù)一
開始做任務(wù)三
完成任務(wù)三,耗時(shí):501毫秒
完成任務(wù)二,耗時(shí):1001毫秒
完成任務(wù)一,耗時(shí):2001毫秒
參考原創(chuàng): 翟永超