1、創建
@Configuration
public class ThreadPoolConfig {
/**
* 創建線程池
*/
@Bean(name = "threadPool")
public ThreadPoolTaskExecutor creatPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(16); // 核心線程數目
executor.setMaxPoolSize(64); // 指定最大線程數
executor.setQueueCapacity(320); // 隊列中最大的數目
executor.setThreadNamePrefix("taskThreadPool_"); // 線程名稱前綴
// rejection-policy:當pool已經達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執行任務,而是由調用者所在的線程來執行
// 對拒絕task的處理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setKeepAliveSeconds(60); // 線程空閑后的最大存活時間
executor.initialize();
return executor;
}
}
2、使用
@Resource(name = "threadPool")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Test
void jiecTest(){
threadPoolTaskExecutor.execute(()->{
for(int i=1;i<=200;i++){
System.out.println("線線程1:"+i);
}
});
threadPoolTaskExecutor.execute(()->{
for(int i=200;i>0;i--){
System.out.println("線線程2:"+i);
}
});
}
3、提交任務
無返回值的任務使用execute(Runnable)
有返回值的任務使用submit(Runnable)