completableFeture常用方法

 

Future 是Java 5添加的类,用来描述一个异步计算的结果。前文中,我们领略了 Future 的便利,但它还是存在诸多不足,比如:

  • Future 对于结果的获取很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然是效率低下的,轮询的方式又十分耗费CPU资源,而且也不能保证实时得到计算结果。

  • Future难以解决线程执行结果之间的依赖关系,比如一个线程等待另一个线程执行结束再执行,以及两个线程执行结果的合并处理等。

Java8带来了 CompletableFuture,CompletableFuture类实现了CompletionStage和Future接口,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

 

1 静态方法

CompletableFuture 提供了几个静态方法来创建一个异步操作:

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {...}
​
 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {...}
 
 public static CompletableFuture<Void> runAsync(Runnable runnable) {...}
 
 public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {...}
  
 public static Completab}leFuture<Void> allOf(CompletableFuture<?>... cfs) {...}
 
 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {...}

1.1 supplyAsync

该方法接受一个Supplier接口,在异步操作完成后返回一个结果。

CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(
                () -> {
                    return "supplyAsync";
                }
        );
        String s = stringCompletableFuture.get();
        System.out.println(s);

supplyAsync(Supplier<U> supplier, Executor executor):可以指定线程池。

没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。

1.2 runAsync

该方法接受一个Runnable接口,没有返回值。

Runnable runnable = () -> {
            System.out.println("runnable");
        };
        CompletableFuture.runAsync(runnable).get();

1.3 allOf

该方法接受多个CompletableFuture,它会等待所有异步操作执行完毕

        CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
            System.out.println("t1执行完");
        });
​
        CompletableFuture<Void> t2 = CompletableFuture.runAsync(() -> {
            System.out.println("t2执行完");
        });
        
        CompletableFuture.allOf(t1, t2).join();
​
        System.out.println("allOf");

输出: t1执行完 t2执行完 allOf

 

如果异步操作t2发生异常会怎样

CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
            System.out.println("t1执行完");
        });
​
        CompletableFuture<Void> t2 = CompletableFuture.runAsync(() -> {
            int n = 1/0;
            System.out.println("t2执行完");
        });
​
        CompletableFuture.allOf(t1, t2);
​
        System.out.println("allOf");

 

注意:即使有个异步操作报异常,也还是往下走

如果要接受异步操作的异常,并进行处理,可以使用exceptionally()方法(返回新的CompletableFuture)

CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
            System.out.println("t1执行完");
        });
​
        CompletableFuture<Void> t2 = CompletableFuture.runAsync(() -> {
            int n = 1/0;
            System.out.println("t2执行完");
        });
​
        CompletableFuture<Void> exceptionally = CompletableFuture.allOf(t1, t2).exceptionally((e) -> {
            System.out.println(e);
            return null;
        });
​
        System.out.println("allOf");

 

 

1.4 anyOf

只要有一个异步操作执行完毕,就返回。

CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
            System.out.println("t1执行完");
        });
​
        CompletableFuture<Void> t2 = CompletableFuture.runAsync(() -> {
            int n = 1 / 0;
            System.out.println("t2执行完");
        });
​
        CompletableFuture<Object> exceptionally = CompletableFuture.anyOf(t1, t2).exceptionally((e) -> {
            System.out.println(e);
            return null;
        });
​
        System.out.println("allOf");

 

因为t1执行完毕就返回了,t2还没开始执行,所有就没有异常信息打印

如果让t1睡眠2秒, t2先执行,则可以检测到异常

CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1执行完");
        });

 

2.常用方法

2.0 whenComplete | handle

当CompletableFuture的计算结果完成,或者抛出异常的时候,可以使用。 没有返回值

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)
  • Action的类型是BiConsumer<? super T,? super Throwable>,它可以处理正常的计算结果,或者异常情况。

  • 方法不以Async结尾,意味着Action使用相同的线程执行,而Async可能会使用其它的线程去执行(如果使用相同的线程池,也可能会被同一个线程选中执行)。

  • 这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
​
        }
        if (new Random().nextInt() % 2 == 0) {
            int i = 12 / 0;
        }
        System.out.println("执行结束!");
    });
​
    future.whenComplete(new BiConsumer<Void, Throwable>() {
        @Override
        public void accept(Void t, Throwable action) {
            System.out.println("执行完成!");
        }
    });
​
    future.exceptionally(new Function<Throwable, Void>() {
        @Override
        public Void apply(Throwable t) {
            System.out.println("执行失败:" + t.getMessage());
            return null;
        }
    }).join();

有返回值

public <U> CompletableFuture<U>     handle(BiFunction<? super T,Throwable,? extends U> fn)
public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn)
public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)

2.1 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) {} 

thenApply 接收一个函数作为参数,使用该函数处理上一个CompletableFuture 调用的结果,并返回一个具有处理结果的Future对象。

        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            return 1;
        }).thenApplyAsync(i -> {
            int n = i * 2;
            return n;
        });
​
        System.out.println("最终结果: " + integerCompletableFuture.get());

2.2 thenCompose

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) ;

thenCompose 的参数为一个返回 CompletableFuture 实例的函数,该函数的参数是先前计算步骤的结果。

 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(3);
            System.out.println("第一阶段:" + number);
            return number;
        }
    }).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
        @Override
        public CompletionStage<Integer> apply(Integer param) {
            return CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = param * 2;
                    System.out.println("第二阶段:" + number);
                    return number;
                }
            });
        }
    });
    System.out.println("最终结果: " + future.get());

那么 thenApply 和 thenCompose 有何区别呢:

  • thenApply 转换的是泛型中的类型,返回的是同一个CompletableFuture;

  • thenCompose 将内部的 CompletableFuture 调用展开来并使用上一个CompletableFutre 调用的结果在下一步的 CompletableFuture 调用中进行运算,是生成一个新的CompletableFuture

    下面用一个例子对对比:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
​
    CompletableFuture<String> result1 = future.thenApply(param -> param + " World");
    CompletableFuture<String> result2 = future.thenCompose(param -> CompletableFuture.supplyAsync(() -> param + " World"));
​
    System.out.println(result1.get());
    System.out.println(result2.get());

2.3 thenAccept

通过观察该系列函数的参数类型可知,它们是函数式接口Consumer,这个接口只有输入,没有返回值。

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);
 CompletableFuture<Void> voidCompletableFuture = CompletableFuture.supplyAsync(() -> {
            return 1;
        }).thenAccept(n -> {
            System.out.println("返回值:" + n);
        });
​
        System.out.println("最终结果: " + voidCompletableFuture.get());

 

2.4 thenAcceptBoth

thenAcceptBoth 函数的作用是,当两个 CompletionStage 都正常完成计算的时候,就会执行提供的action消费两个异步的结果

public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action,     Executor executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 2);
​
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        } );
​
        future1.thenAcceptBoth(future2, (n1, n2) -> {
            System.out.println("n1: " + n1);
            System.out.println("n2: " + n2);
        }).join();

2.5 thenRun

thenRun 也是对线程任务结果的一种消费函数,与thenAccept不同的是,thenRun 会在上一阶段 CompletableFuture 计算完成的时候执行一个Runnable,Runnable并不使用该 CompletableFuture 计算的结果。

public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

示例

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
        int number = new Random().nextInt(10);
        System.out.println("第一阶段:" + number);
        return number;
    }).thenRun(() ->
            System.out.println("thenRun 执行"));
    System.out.println("最终结果:" + future.get());

2.6 thenCombine

thenCombine 方法,合并两个线程任务的结果,并进一步处理。

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

示例

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(10);
            System.out.println("第一阶段:" + number);
            return number;
        }
    });
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(10);
            System.out.println("第二阶段:" + number);
            return number;
        }
    });
    CompletableFuture<Integer> result = future1.thenCombine(future2, new BiFunction<Integer, Integer, Integer>() {
        @Override
        public Integer apply(Integer x, Integer y) {
            return x + y;
        }
    });
    System.out.println("最终结果:" + result.get());

2.7 applyToEither

两个线程任务相比较,先获得执行结果的,就对该结果进行下一步的转化操作。

public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(3);
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一阶段:" + number);
            return number;
        }
    });
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(3);
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第二阶段:" + number);
            return number;
        }
    });
​
    future1.applyToEither(future2, new Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer number) {
            System.out.println("最快结果:" + number);
            return number * 2;
        }
    }).join();

2.8 acceptEither

两个线程任务相比较,先获得执行结果的,就对该结果进行下一步的消费操作。

public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(3) + 1;
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一阶段:" + number);
            return number;
        }
    });
​
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(3) + 1;
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第二阶段:" + number);
            return number;
        }
    });
​
    future1.acceptEither(future2, new Consumer<Integer>() {
        @Override
        public void accept(Integer number) {
            System.out.println("最快结果:" + number);
        }
    }).join();

2.9 runAfterEither

两个线程任务相比较,有任何一个执行完成,就进行下一步操作,不关心运行结果。

public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(5);
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一阶段:" + number);
                return number;
            }
        });
​
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int number = new Random().nextInt(5);
                try {
                    TimeUnit.SECONDS.sleep(number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第二阶段:" + number);
                return number;
            }
        });
​
        future1.runAfterEither(future2, new Runnable() {
            @Override
            public void run() {
                System.out.println("已经有一个任务完成了");
            }
        }).join();

2.10 runAfterBoth

两个线程任务相比较,两个全部执行完成,才进行下一步操作,不关心运行结果。

public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一阶段:1");
                return 1;
            }
        });
​
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第二阶段:2");
                return 2;
            }
        });
​
        future1.runAfterBoth(future2, new Runnable() {
            @Override
            public void run() {
                System.out.println("上面两个任务都执行完成了。");
            }
        }).get();

 

参考文档: https://cloud.tencent.com/developer/article/1698359

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_中年人

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值