1、CompletableFuture的静态方法,创建CompletableFuture实例
(1)runAsync(Runnable runnable),其中future.get方法会阻塞,无返回值
CompletableFuture future = CompletableFuture.runAsync(() ->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runasync");
});
System.out.println(11111);
future.get();
System.out.println(2222222);
(2)supplyAsync(Supplier<U> supplier),该方法有返回值
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync:" + Thread.currentThread());
return "supply";
});
System.out.println(future.get());
(3)上述两个静态方法使用的线程池是默认线程池,如果需要指定线程池,可以使用如下两个方法
runAsync(Runnable runnable, Executor executor)
supplyAsync(Supplier<U> supplier, Executor executor)
2、对于Future,提交任务后,只能调用get()等待返回结果,CompletableFuture可以在结果上加上一个callback,当得到结果后,再执行callback
(1)thenRun(Runnable runable)
CompletableFuture future = CompletableFuture
.runAsync(() -> System.out.println("runasync"),executor)
.thenRun(() -> System.out.println("thenRun"));
future.get();
System.out.println("end");
(2)thenAccept (Consumer<? super T> action),可以消费上一个任务的返回结果,但thenAccept本身没有返回值
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync:" + Thread.currentThread());
return "supply";
}).thenAccept(str -> System.out.println("thenapplay:" + str.length()));
System.out.println(future.get()); // 无返回值
(3)thenApply(Function fn),与thenAccept相似可以处理上一个任务的返回值,但thenApply可以有自己的返回值
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync:" + Thread.currentThread());
return "supply";
}).thenApply(str -> {
System.out.println("thenapplay:" + Thread.currentThread());
return str.length();
});
System.out.println(future.get()); // 返回6
3、thenCompose与thenCombine
(1) thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)将两个异步操作流进行流水线
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync:" + Thread.currentThread());
return "supply";
}).thenCompose(str -> CompletableFuture.supplyAsync(str::length));
// 此处是第二个异步线程,thenApply执行的任务不是异步的,是在主线程中完成
System.out.println(future.get());// 返回 6
(2)thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn),将两个异步线程的结果进行处理
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync:" + Thread.currentThread());
return "supply";
}).thenCombine(CompletableFuture.supplyAsync(() -> 6), (str, length) -> str.length() + length);
System.out.println(future.get()); // 返回12 ,将第一个任务返回的"supply"的长度加上第二个任务返回的6
4、任意多个CompletableFuture的组合
(1)public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs),表示"与"操作,返回的是CompletableFuture<Void>,会等到所有任务都完成才结束
(2)public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs),表示"或"操作,返回的是CompletableFuture<Object>,只要有一个任务完成,就结束