SpringBoot2 線程池的定義和使用

SpringBoot2 線程池的定義和使用

定義線程池

<code>@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());
};

}
}/<code>

如何使用

<code>@Autowired    
private ThreadPoolTaskExecutor threadPoolTaskExecutor;

public void test(){
CompletableFuture<void> userFuture = CompletableFuture.runAsync(() -> System.out.println(111), threadPoolTaskExecutor);
}/<void>/<code>

趙小胖個人博客


分享到:


相關文章: