@Autowired
private ThreadPoolExecutor executor;
//开启线程 supplyAsync() 是可以拿到任务执行够的返回值
//runAsync() 返回的是void
CompletableFuture<Void> task01= CompletableFuture.runAsync(() -> {
// 业务代码
}, executor);
CompletableFuture<Void> task02= CompletableFuture.runAsync(() -> {
// 业务代码
}, executor);
CompletableFuture<Void> task03= CompletableFuture.runAsync(() -> {
// 业务代码
}, executor);
// 阻塞等待所有的任务执行完成 才可以执行下一步
// anyOf()等待其中一个线程完成就可以执行主线程了
CompletableFuture.allOf(task01, task02, task03).get();
//主线程执行
return null;
===========注入线程池===============
@Configuration
public class MyThreadConfig {
@Bean
@Primary
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool) {
return new ThreadPoolExecutor(pool.getCoreSize(),
pool.getMaxSize(), pool.getKeepAliveTime(),
TimeUnit.SECONDS, new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
}
@ConfigurationProperties(prefix = "xxx.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
yaml 位置加上下面参数
xxx:
thread:
core-size: 20
max-size: 200
keep-alive-time: 10
CompletableFuture异步编排 java8
于 2022-07-21 11:54:01 首次发布