前言
小白今天又来更新啦,上一节内容是 CompletableFuture 实现异步总结(一),今天跟大家分享的是 CompletableFuture 进阶部分。
一、CompletableFuture 提供了哪些方法?
对于 CompletableFuture 来说,我们会发现它本身提供了很多方法供开发使用,例如参考下面的小部分截图。
二、CompletableFuture 常用的回调方法
1.thenApply( )
thenApply( )方法:可以用于获取异步任务的结果。
CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> {
return "KARRY_wang_123";
});
CompletableFuture<String> stringCompletableFuture = supplyAsync.thenApply(str -> {
String lowerCase = str.toLowerCase();
return lowerCase;
});
//打印异步结果
System.out.println(stringCompletableFuture.get());
2.thenAccept( )
thenAccept( )方法:在异步任务运行完成之后,需要结合上一步的结果,并处理一些次要代码。
CompletableFuture.supplyAsync(() -> {
String code = "karry_wang";
return code;
}).thenAccept((code) -> {
System.out.println("code = " + code);
});
3. thenRun( )
thenRun( ) 方法:可以适用于当异步任务完成后,不使用上一步异步任务的结果,且可以得知异步是否完成的通知。
CompletableFuture.supplyAsync(() -> {
String code = "karry_wang";
return code;
}).thenAccept((code) -> {
System.out.println("code = " + code);
}).thenRun(() -> {
System.out.println("处理完成....");
});
三、CompletableFuture 之异常处理
1. 异常处理方法对比如下:
方法名 | 不同点 |
exceptionally( ) | 且常用于异步任务的末端进行异常处理; |
handle( ) | 用于针对某一个异步任务进行异常修复; |
2. 代码示例:
(1)exceptionally( )方法:
CompletableFuture.supplyAsync(() -> {
String code = null;
//代码运行到下面这行会报空指针异常,CompletableFuture 直接进入异常处理,
//即执行 exceptionally 方法
int length = code.length();
return length;
}).thenAccept((code) -> {
System.out.println("code = " + code);
}).thenRun(() -> {
System.out.println("处理完成....");
}).exceptionally(ex -> {
System.out.println("ex = " + ex);
return null;
});
(2)handle( )方法:
CompletableFuture.supplyAsync(() -> {
String code = null;
int length = code.length();
return length;
}).handle((result, ex)-> {
//上面的异步任务如果没有异常,则直接返回result,否则进入if相关的异常判断,打印异常
if (ex != null){
System.out.println("异常 = " + ex);
}
return result;
});
补充:
这两个方法用于区别所使用的线程来源于哪个线程池,比如带有线程池入参的方法为自定义的线程池,且这两个方法对JDK的版本有要求,需要 JDK17+
CompletableFuture<R> exceptionallyAsync(Function<Throwable, R> fn)
CompletableFuture<R>exceptionallyAsync(Function<Throwable,R> fn,Executor executor)
今天的分享就到这啦,有什么问题还请各位大佬多多赐教哈,忙去喽~