CompleteFuture 快速入门

313 阅读6分钟

文章摘自:juejin.cn/post/703847…

1.静态方法

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) ; public  static <U> CompletableFuture<U> completedFuture (U value) ; 

在这四个方法中,run开头的代表创建一个没有返回值的异步任务,supply开头的方法代表创建一个具备返回值的异步任务。同时这两类方法都支持指定执行线程池,如果不指定执行线程池,CompletableFuture则会默认使用ForkJoinPool.commonPool()线程池内的线程执行创建出的异步任务

案例:

public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture cf =
                CompletableFuture.supplyAsync(CompletableFutureDemo::evenNumbersSum)
                    // 链式编程:基于上个任务的返回继续执行新的任务
                    .thenApply(r -> {
                        System.out.println("获取上个任务的执行结果:" + r);
                        // 通过上个任务的执行结果完成计算:求和100所有数
                        return r + oddNumbersSum();
                    }).thenApplyAsync(r -> {
                        System.out.println("获取上个任务的执行结果:" + r);
                        Integer i = r / 0; // 拋出异常
                        return r;
                    }).handle((param, throwable) -> {
                        if (throwable == null) {
                            return param * 2;
                        }
                        // 获取捕获的异常
                        System.out.println(throwable.getMessage());
                        System.out.println("我可以在上个任务" +
                                "抛出异常时依旧执行....");
                        return -1;
                    }).thenCompose(x -> 
                        CompletableFuture.supplyAsync(() -> x+1
                    )).thenRun(() -> {
                        System.out.println("我是串行无返回任务....");
                });

        // 主线程执行休眠一段时间
        // 因为如果不为CompletableFuture指定线程池执行任务的情况下,
        // CompletableFuture默认是使用ForkJoinPool.commonPool()的线程
        // 同时是作为main线程的守护线程进行的,如果main挂了,执行异步任
        // 务的线程也会随之终止结束,并不会继续执行异步任务
        Thread.sleep(2000);
    }

    // 求和100内的偶数
    private static int evenNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) sum += i;
        }
        return sum;
    }

    // 求和100内的奇数
    private static int oddNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) sum += i;
        }
        return sum;
    }
}

2.下一个任务依赖于上一个任务的执行结果时

// 可以基于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 <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, 
                                    ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, 
                                    ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, 
                                    ? extends U> fn,Executor executor);

// 可以基于CompletableFuture对象接着创建一个无返回任务
CompletionStage<Void> thenRun(Runnable action); 
CompletionStage<Void> thenRunAsync(Runnable action); 
CompletionStage<Void> thenRunAsync(Runnable action,Executor executor); 

// 与thenApply方法类似,但是thenApply方法操作的是同一个CompletableFuture
// 而该类方法则是生产新的CompletableFuture<返回值>对象进行操作
public <U> CompletableFuture<U> thenCompose(Function<? super T, 
                        ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(
        Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, 
                ? extends CompletionStage<U>> fn,Executor executor)
  • ①thenApply类:此类方法可以基于上一个任务再创建一个新的有返回型任务。
  • ②handle类:与thenApply类作用相同,不同点在于thenApply类方法只能在上一个任务执行正常的情况下才能执行,当上一个任务执行抛出异常后则不会执行。而handle类在上个任务出现异常的情况下也可以接着执行。
  • ③thenRun类:此类方法可以基于上一个任务再创建一个新的无返回型任务。
  • ④thenCompose类:与thenApply类大致相同,不同点在于每次向下传递都是新的CompletableFuture对象,而thenApply向下传递的都是同一个CompletableFuture对象对象

案例:

public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture cf =
                CompletableFuture.supplyAsync(CompletableFutureDemo::evenNumbersSum)
                    // 链式编程:基于上个任务的返回继续执行新的任务
                    .thenApply(r -> {
                        System.out.println("获取上个任务的执行结果:" + r);
                        // 通过上个任务的执行结果完成计算:求和100所有数
                        return r + oddNumbersSum();
                    }).thenApplyAsync(r -> {
                        System.out.println("获取上个任务的执行结果:" + r);
                        Integer i = r / 0; // 拋出异常
                        return r;
                    }).handle((param, throwable) -> {
                        if (throwable == null) {
                            return param * 2;
                        }
                        // 获取捕获的异常
                        System.out.println(throwable.getMessage());
                        System.out.println("我可以在上个任务" +
                                "抛出异常时依旧执行....");
                        return -1;
                    }).thenCompose(x -> 
                        CompletableFuture.supplyAsync(() -> x+1
                    )).thenRun(() -> {
                        System.out.println("我是串行无返回任务....");
                });

        // 主线程执行休眠一段时间
        // 因为如果不为CompletableFuture指定线程池执行任务的情况下,
        // CompletableFuture默认是使用ForkJoinPool.commonPool()的线程
        // 同时是作为main线程的守护线程进行的,如果main挂了,执行异步任
        // 务的线程也会随之终止结束,并不会继续执行异步任务
        Thread.sleep(2000);
    }

    // 求和100内的偶数
    private static int evenNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) sum += i;
        }
        return sum;
    }

    // 求和100内的奇数
    private static int oddNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) sum += i;
        }
        return sum;
    }
}

3.其他操作

// 阻塞主线程获取执行结果(与FutureTask.get()一致)
public T get();
// 上个方法的超时版本
public T get(long timeout,TimeUnit unit);
// 尝试获取执行结果,执行完成返回执行结果,未完成返回任务参数
public T getNow(T valueIfAbsent);
// 阻塞主线程等待任务执行结束
public T join();
// 无返回的异步任务正常执行完成后可以通过此方法写出返回值
public boolean complete(T value);
// 无返回的异步任务执行异常后可以通过此方法写出捕获的异常信息
public boolean completeExceptionally(Throwable ex);

// 任务正常执行完成后的回调函数:默认由执行任务的线程执行回调逻辑
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 任务正常执行完成后的回调函数:另启一条线程执行回调逻辑
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
// 任务正常执行完成后的回调函数:指定线程池执行回调逻辑
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,
                                Executor executor);
// 执行过程中出现异常时执行的回调方法
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
                                
// 执行结束后会执行的回调逻辑
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)

①主线程调用直接获取执行结果的get、getNow方法

②可以为无返回值的异步任务写出执行结果的:complete开头的方法

②任务正常执行成功的回调:thenAccept开头的方法

④任务执行抛出异常的回调:exceptionally方法

⑤任务执行结束的回调:whenComplete开头的方法

4.任务之间的汇聚功能

AND类型:

  • thenCombine系列:可以接收前面任务的结果进行汇聚计算,并且计算后可以返回值
  • thenAcceptBoth系列:可以接收前面任务的结果进行汇聚计算,但计算后没有返回值
  • runAfterBoth系列:不可以接收前面任务的结果且无返回,但可以在任务结束后进行汇聚计算
  • CompletableFuture类的allOf系列:不可接收之前任务的结果,但可以汇聚多个任务,但是要配合回调处理方法一起使用

OR类型:

  • applyToEither系列:接收最先完成的任务结果进行处理,处理完成后可以返回值
  • acceptEither系列:接收最先完成的任务结果进行处理,但是处理完成后不能返回
  • runAfterEither系列:不能接收前面任务的返回值且无返回,单可以为最先完成的任务进行后继处理
  • CompletableFuture类的anyOf系列:可以同时汇聚任意个任务,并接收最先执行完成的任务结果进行处理,处理完成后没有返回值,需要配合回调方法一起使用
public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        /*--------------------创建两个异步任务CF1/CF2------------------*/
        CompletableFuture<Integer> cf1 =
                CompletableFuture.supplyAsync(CompletableFutureDemo::evenNumbersSum);
        CompletableFuture<Integer> cf2 =
                CompletableFuture.supplyAsync(CompletableFutureDemo::oddNumbersSum);

        /*--------------------测试AND类型汇聚方法------------------*/
        CompletableFuture<Integer> cfThenCombine = cf1.thenCombine(cf2, (r1, r2) -> {
            System.out.println("cf1任务计算结果:" + r1);
            System.out.println("cf2任务计算结果:" + r2);
            return r1 + r2;
        });
        System.out.println("cf1,cf2任务ThenCombine汇聚处理结果:" + cfThenCombine.get());

        // thenAcceptBoth、runAfterBoth系列与thenCombine差不多相同
        // 区别就在于入参BiFunction、BiConsumer、Runnable三个函数式接口的不同

        // 使用allOf汇聚两个任务(可以汇聚多个)
        CompletableFuture cfAllOf = CompletableFuture.allOf(cf1, cf2);
        // 配合thenAccept成功回调函数使用
        cfAllOf.thenAccept( o -> System.out.println("所有任务完成后进行断后处理...."));

        //分割线
        Thread.sleep(2000);
        System.err.println("--------------------------------------");

        /*--------------------测试OR类型汇聚方法------------------*/
        CompletableFuture<Integer> cfApplyToEither = cf1.applyToEither(cf2, r -> {
            System.out.println("最先执行完成的任务结果:" + r);
            return r * 10;
        });
        System.out.println("cf1,cf2任务applyToEither汇聚处理结果:"+cfApplyToEither.get());


        // acceptEither、runAfterEither系列与applyToEither系列也差不多相同
        // 区别就也是在于入参BiFunction、BiConsumer、Runnable三个函数式接口的不同

        // 使用anyOf汇聚两个任务,谁先执行完成就处理谁的执行结果
        CompletableFuture cfAnyOf = CompletableFuture.anyOf(cf1, cf2);
        // 配合thenAccept成功回调函数使用
        cfAnyOf.thenAccept(r -> {
            System.out.println("最先执行完成的任务结果:" + r);
            System.out.println("对先完成的任务结果进行后续处理....");
        });
    }

    // 求和100内的偶数
    private static int evenNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(800); // 模拟耗时
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) sum += i;
        }
        return sum;
    }

    // 求和100内的奇数
    private static int oddNumbersSum() {
        int sum = 0;
        try {
            Thread.sleep(1000); // 模拟耗时
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) sum += i;
        }
        return sum;
    }
}