1.创建CompletableFuture对象
runAsync方法:它以Runnabel函数式接口类型为参数,计算结果为空。
supplyAsync方法以Supplier函数式接口类型为参数,计算结果类型为U。
public static CompletableFuture
public static CompletableFuture
public static CompletableFuture supplyAsync(Supplier supplier)
public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
2.结果变换
public CompletionStage thenApply(Function super T,? extends U> fn);
public CompletionStage thenApplyAsync(Function super T,? extends U> fn);
public CompletionStage thenApplyAsync(Function super T,? extends U> fn,Executor executor);
String result = CompletableFuture.supplyAsync(()->{
return "hello";
}).thenApplyAsync(v->"world").join();
System.out.println(result); --》world
3.消费结果
public CompletionStage
public CompletionStage
public CompletionStage
CompletableFuture.supplyAsync(()->{
return "hello";
}).thenAccept(v->{
System.out.println("consume: " +v); --->consume: hello
});
4.结合两个CompletionStage的结果,进行转化后返回
public CompletionStage
public CompletionStage
public CompletionStage
需要上一阶段的返回值,并且other代表的CompletionStage也要返回值之后,把这两个返回值,进行转换后返回指定类型的值。
String result = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}),(s1,s2)->{return s1 +"--" + s2;}).join();
System.out.println(result);-->hello--world
5.两个CompletionStage,谁计算的快,就用那个CompletionStage的结果进行下一步的处理
public CompletionStage applyToEither(CompletionStage extends T> other,Function super T, U> fn);
public CompletionStage applyToEitherAsync(CompletionStage extends T> other,Function super T, U> fn);
public CompletionStage applyToEitherAsync(CompletionStage extends T> other,Function super T, U> fn,Executor executor);
String result = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(300);
}catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).applyToEitherAsync(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(100);
}catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}), (s)->{return "处理结果最快的是" +s; }
).join();
System.out.println(result);
6.行时出现了异常,可以通过exceptionally进行补偿
public CompletionStage
String message =CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
if(true){
throw new RuntimeException("exception is run");
}
return "hello wolrd";
}).exceptionally(e->{
System.out.println(e.getMessage());
return "world hello";
}).join();
System.out.println(message); -->java.lang.RuntimeException: exception is run
world hello