SpringBoot2 線程池的定義和使用
定義線程池
@Slf4j
@EnableAsync
@Configuration
public class AsyncExecutorConfig implements AsyncConfigurer {
@Bean
public ThreadPoolTaskExecutor asyncServiceExecutor() {
//返回可用處理器的虛擬機的最大數量不小於1
int cpu = Runtime.getRuntime().availableProcessors();
log.info("start asyncServiceExecutor cpu : {}", cpu);
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心線程數
executor.setCorePoolSize(cpu);
//配置最大線程數
executor.setMaxPoolSize(cpu);
//配置隊列大小
executor.setQueueCapacity(50);
//用來設置線程池關閉的時候等待所有任務都完成再繼續銷毀其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
//設置線程池中任務的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應用最后能夠被關閉,而不是阻塞住
executor.setAwaitTerminationSeconds(60);
//配置線程池中的線程的名稱前綴
executor.setThreadNamePrefix("async-service-");
// rejection-policy:當pool已經達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
// 使用預定義的異常處理類
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//執行初始化
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return asyncServiceExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (throwable, method, objects) -> {
StringBuilder sb = new StringBuilder();
for (Object param : objects) {
sb.append(param).append(",");
}
log.error("Exception message - {},Method name - {},Parameter value - {}", throwable.getMessage(), method.getName(), sb.toString());
};
}
}
如何使用
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public void test(){
CompletableFuture<Void> userFuture = CompletableFuture.runAsync(() -> System.out.println(111), threadPoolTaskExecutor);
}