1.概述
在jdk1.8中,引入了CompletableFuture,它扩展了Future和CompletionStage,可以在任务完成后触发回调,实现异步调用。在此之前若要设置回调一般会使用guava的ListenableFuture,但引入回调之后会陷入无穷的回调地狱中,导致编码难以阅读和理解。CompletableFuture对Future进行了扩展,可以通过设置回调的方式处理计算结果,同时也支持组合,支持任务编排,在一定程度上解决了回调地狱和代码难以阅读问题。本文将分析CompletableFuture的使用及实现原理。
2.案例分析
2.1 CompletableFuture使用
2.1.1 创建CompletableFuture
1.利用 runAsync(Runnable runnable)创建
runAsync方法入参是Runnable、executor,如果入参有executor,则使用executor来执行异步任务。需要注意的是,runAsync方法只执行方法里面内容,不携带返回结果。
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
//使用runAsync(Runnable runnable)创建CompletableFuture对象如下
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
try {
//Thread.sleep(1000);
System.out.println("runAsync " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
});
//使用runAsync(Runnable runnable, Executor executor)创建CompletableFuture对象
final ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
try {
//Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("runAsync " + Thread.currentThread().getName());
}, executorService);
2.利用supplyAsync(Supplier supplier)创建
supplyAsync(Supplier supplier)异步执行并返回结果的任务,适合需要返回值的场景。
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
//使用supplyAsync(Runnable runnable)创建CompletableFuture对象如下
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
try {
//Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("supplyAsync " + Thread.currentThread().getName());
return "hello";
});
//使用supplyAsync(Runnable runnable,Executor executor)创建CompletableFuture对象如下
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
try {
//Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("supplyAsync " + Thread.currentThread().getName());
return "hello";
}, executorService);
2.1.2 完成complete和取消cancel操作
complete(V value):手动完成CompletableFuture,强制设置返回结果;
cancel(boolean mayInterruptIfRunning):取消任务,入参为true表明中断正在执行的任务;
//强制设置返回结果,即使任务有返回结果,也会被complete强制返回结果替代
public static String complete() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() ->

最低0.47元/天 解锁文章
359

被折叠的 条评论
为什么被折叠?



