1、 runAsync 和 supplyAsync方法
CompletableFuture 提供了四个静态方法来创建一个异步操作。
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。
- runAsync方法不支持返回值。
- supplyAsync可以支持返回值。
2、异常处理
exceptionally(Function<Throwable,? extends T> fn)
在exceptionally方法中可以处理future的抛出的异常。但是在exceptionally方法中有异常怎么办,分两种情况:
1、CheckedException 首先是不允许在apply方法上加异常声明的,因为接口定义没有抛出异常,所以只能try/catch。
2、RuntimeExction 异常不会被上层接口捕获,异常后面的代码也不会执行,就是说会中断。在下面的示例中,“main exception“不会被打印,”after“也不会被打印,exceptionally方法返回结果也不会有。
所以在exceptionally方法建议用try/catch环绕,当然更好的是在产生Fucture的run方法中用try/catch环绕,即示例中的 ”12/0“ 放到try语句中。
示例
public static void main(String[] args) {
try {
whenComplete();
} catch (Exception e) {
System.out.println("main exception");
}
}
public static void whenComplete() throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
int i = 12/0;
System.out.println("run end ...");
return "---";
});
CompletableFuture<String> exceptionallyResult=future.exceptionally(new Function<Throwable, String>() {
@Override
public String apply(Throwable t) {
System.out.println("执行失败!"+t.getMessage());
int i = 12/0;
// if(1>0){
// throw new Exception("24");
// }
System.out.println("after");
return "exceptionally result";
}
});
System.out.println(exceptionallyResult.get());
TimeUnit.SECONDS.sleep(2);
}
2、计算结果完成时的回调方法
当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:---------
public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T>
可以看到Action的类型是BiConsumer<? super T,? super Throwable>它可以处理正常的计算结果,或者异常情况。
whenComplete 和 whenCompleteAsync 的区别:
whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。
whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。
3、 thenApply 方法
当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化。
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
Function<? super T,? extends U>
T:上一个任务返回结果的类型
U:当前任务的返回值类型
thenApply和whenComplete区别在于如果线程抛出异常前者不会执行,反之如果保证不会抛出异常,一般用前者,因为比较简单。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。