jdk1.8才算是真正支持了异步操作,利用jdk1.8中提供的lambada表达式,借助CompletableFuture可以实现异步的操作,同时lambada又大大简化了代码量。
CompletableFuture的使用详解:
a.创建异步操作的方法
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可以支持返回值。
b.在异步操作完成时的回调方法
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> exceptionally(Function<Throwable,? extends T> fn)
whenComplete方法和whenCompleteAsync方法是当异步操作执行完之后执行操作的方法,他们两个的区别是做前者用之前的线程进行,后者则是使用线程池来执行
exceptionally则是出现异常的时候执行操作的方法
c.串行化方法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)