创建线程池:
1. 自己创建线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor( 5, //core 10, //Max 15, //keepAliveTime TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy() );
2. 如果在springboot项目中,可以直接注入如下的线程池使用:
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor ;
使用线程池:
//异步执行 CompletableFuture<Void> xxxFuture = CompletableFuture.runAsync( () -> { //TODO 业务逻辑 }, threadPoolTaskExecutor); //异步执行 CompletableFuture<Void> yyyFuture = CompletableFuture.runAsync( () -> { //TODO 业务逻辑 }, threadPoolTaskExecutor); //等待执行完成 CompletableFuture.allOf(xxxFuture, yyyFuture).get();