1、介绍
CompletabelFure在java8中提出,在java9中完善
CompletableFuture类分别实现了Future接口和CompletionStage接口

2、使用
2.1 多任务并行进行,后统一合并
List<CompletableFuture<String>> completableFutureList = new ArrayList<>();
CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "-->1";
});
CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "-->2";
});
CompletableFuture<String> completableFuture3 = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "-->3";
});
CompletableFuture allCompletableFuture = CompletableFuture.allOf(completableFuture1,completableFuture2,completableFuture3);
allCompletableFuture.get();
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis()+":"+completableFuture1.get());
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis()+":"+completableFuture2.get());
System.out.println(Thread.currentThread().getName() +":"+ System.currentTimeMillis()+":"+completableFuture3.get());
输出结果
ForkJoinPool.commonPool-worker-1:1642580353710
ForkJoinPool.commonPool-worker-2:1642580353711
ForkJoinPool.commonPool-worker-3:1642580353711
main:1642580356711:-->1
main:1642580356711:-->2
main:1642580356711:-->3
网友评论