CompletableFuture - JiyangM/spring GitHub Wiki

创建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)

通过以上方法创建一个CompletableFuture,传一个Runnable或者Supplier对象,这个对象区别就是Runnable无返回值,而Supplier有返回值,然后再通过thenxxx()方法执行上一个CompletableFuture的执行结果,这个方法可实现异步执行而不会阻塞主线程

转换

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)

消费

public CompletableFuture<Void> 	thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> 	thenAcceptAsync(Consumer<? super T> action)
public CompletableFuture<Void> 	thenAcceptAsync(Consumer<? super T> action, Executor executor)

以上两类方法都可以异步执行,区别是转换有返回值,纯消费无返回值,通常出消费在异步执行链中的末端位置,执行最终的处理, 而转换通常处于还需要继续对执行结果进行下一步处理的时候用;无Async后缀的方法继续在当前线程处理,而有Async后缀的可以在其它线程处理上一个执行结果。


等待两个异步任务结束->无返回值->runAsync

CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {

            try {
                System.out.println("f1 开始");
                Thread.sleep(4000L);
                System.out.println("f1 睡完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        CompletableFuture<Void> futur2 = CompletableFuture.runAsync(() -> {

            try {
                System.out.println("f2 开始");
                Thread.sleep(2000L);
                System.out.println("f2 睡完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture.allOf(futur2,future1).join();
f1 开始
f2 开始
f2 睡完
f1 睡完

具有返回值的异步任务->有返回值->applyAsync

Person person = new Person();
        CompletableFuture<Person> personCompletableFuture1 =
            CompletableFuture.completedFuture(person).thenApplyAsync(person1 -> {
                try {
                    System.out.println("f1 开始");
                    Thread.sleep(2000L);
                    System.out.println("f1 睡完");
                    person1.setAge(20);
                } catch (InterruptedException e) {

                }
                return person;
            });

        CompletableFuture<Person> personCompletableFuture2 =
            CompletableFuture.completedFuture(person).thenApplyAsync(person1 -> {
                try {
                    System.out.println("f2 开始");
                    Thread.sleep(4000L);
                    System.out.println("f2 睡完");
                    person1.setName("df");
                } catch (InterruptedException e) {

                }
                return person;
            });

        CompletableFuture.allOf(personCompletableFuture1,personCompletableFuture2).join();
        System.out.println(person.toString());
f1 开始
f2 开始
f1 睡完
f2 睡完

对列表数据操作 等待所有事件完成开启 另一个事件

StringBuilder result = new StringBuilder();
        List messages = Arrays.asList("a", "b", "c");
        List<CompletableFuture> futures = messages.stream()
                                                  .map(msg -> CompletableFuture.completedFuture(msg).thenApplyAsync(
                                                      s -> delayedUpperCase(s)))
                                                  .collect(Collectors.toList());
        CompletableFuture allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
                                                   .whenComplete((v, th) -> {
                                                       futures.forEach(cf -> assertTrue(isUpperCase(cf.getNow(null))));
                                                       result.append("done");
                                                   });
        allOf.join();
        assertTrue("Result was empty", result.length() > 0);

https://juejin.im/post/5d4c1bfef265da03be48c623

⚠️ **GitHub.com Fallback** ⚠️