java8線程池創(chuàng)建并使用
1、創(chuàng)建
@Configuration
public class ThreadPoolConfig {
/**
* 創(chuàng)建線程池
*/
@Bean(name = "threadPool")
public ThreadPoolTaskExecutor creatPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(16); // 核心線程數(shù)目
executor.setMaxPoolSize(64); // 指定最大線程數(shù)
executor.setQueueCapacity(320); // 隊列中最大的數(shù)目
executor.setThreadNamePrefix("taskThreadPool_"); // 線程名稱前綴
// rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時候,如何處理新任務(wù)
// CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是由調(diào)用者所在的線程來執(zhí)行
// 對拒絕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、提交任務(wù)
無返回值的任務(wù)使用execute(Runnable)
有返回值的任務(wù)使用submit(Runnable)

浙公網(wǎng)安備 33010602011771號