使用spring的ThreadPoolTaskExecutor作为线程池配置异步任务
@Bean(“taskExecutor”)
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(50);
executor.setKeepAliveSeconds(50);
executor.setThreadNamePrefix("-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Resource(name = "taskExecutor")
private ThreadPoolTaskExecutor taskExecutor;
CompletableFuture future1 = CompletableFuture.runAsync(() -> {}, taskExecutor);
CompletableFuture future2 = CompletableFuture.runAsync(() -> {}, taskExecutor);
CompletableFuture all= CompletableFuture.allOf(future1,future2);
all.join();