如果有多个异步任务 希望在前两个异步任务完成之后在执行的任务
thenCombine :可以获取前面两线程的返回结果,本身也有返回结果
* thenAcceptBoth:可以获取前面两线程的返回结果,本身没有返回结果
* runAfterBoth:不可以获取前面两线程的返回结果,本身也没有返回结果
public class CompletableFutureDemo03 {
private static ThreadPoolExecutor executor=new ThreadPoolExecutor(5,
50,
10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
//运行时发现 线程会阻塞 等待新的任务去调度
/**
*
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("线程1开始了" + Thread.currentThread().getName());
int i = 100 / 10;
System.out.println("线程1结束了" + Thread.currentThread().getName());
return i;
}, executor);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("线程2开始了" + Thread.currentThread().getName());
int i = 100 / 5;
System.out.println("线程2结束了" + Thread.currentThread().getName());
return i;
}, executor);
//希望在future1 future2 任务执行完之后 执行future3
//runAfterBothAsync 不能获取前面两个线程的返回结果 本身也没有返回结果
CompletableFuture<Void> voidCompletableFuture = future1.runAfterBothAsync(future2, () -> {
System.out.println("线程3执行了");
},executor);
//thenAcceptBothAsync 可以获取前面两个线程返回结果 本身没有返回结果
future1.thenAcceptBothAsync(future2, (f1, f2) -> {
System.out.println("f1 = " + f1+" "+Thread.currentThread().getName());
System.out.println("f2 = " + f2+" "+Thread.currentThread().getName());
},executor);
//thenCombineAsync 既可以获取前面两个线程的返回结果 同时也会返回结果给阻塞的线程
CompletableFuture<Integer> objectCompletableFuture = future1.thenCombineAsync(future2, (f1, f2) -> {
System.out.println("f1 = " + f1);
System.out.println("f2 = " + f2);
return f1+f2;
}, executor);
System.out.println("objectCompletableFuture:"+objectCompletableFuture.get());
//System.out.println("future:"+future1.get());
}
}