CompletableFuture的运用

it2025-10-20  6

1异步处理在工作中时常用,特此总结一些:目前用的 多点的就是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)

其中 Supplier可以理解创建对象的工厂  里面只有一个抽象的方法 get()

List<String> list=Lists.newArrayList(); String [] a={"1","2","3","4","5","6"}; list.addAll(Arrays.asList(a)); list.forEach(e->CompletableFuture.runAsync(()->{ System.out.println(e); try { TimeUnit.NANOSECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } }));

打印结果 1 4 2 5 3 6

初步实现了异步    

然后 runAsync  的方法都是没有返回值的  supplyAsync带有返回值

2、计算结果完成时的回调方法

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 的区别: whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。 whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。

3、 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)

 

 就这么多吧 

加入一点

     allOf:当所有的CompletableFuture都执行完后执行计算

  anyOf:最快的那个CompletableFuture执行完之后执行计算

CompletableFuture<Void> allFuture = CompletableFuture.allOf(futureA, futureB, futureC, futureD); allFuture.join();

            CompletableFuture.allOf().join(); 会等线程执行完                  allOf()里放入的 是 futures

 

最新回复(0)