CompletableFuture常用方法

获取结果

public T get() 容易形成阻塞
public T get(long timeout, TimeUnit unit) 设置等待时间,超时会报java.util.concurrent.TimeoutException
public T join()
public T getNow(T valueIfAbsent) 若超时就会返回valueIfAbsent的值作为代替

    public static void api1() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> async = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abd";
        });

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        System.out.println(async.get(1L, TimeUnit.SECONDS));
        System.out.println(async.getNow("xxxx"));
    }

主动触发计算

public boolean complete(T value) 是否打断get方法立即返回括号值

    public static void api1() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> async = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abd";
        });

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        System.out.println(async.get(1L, TimeUnit.SECONDS));
        System.out.println(async.complete("complete") + "\t" + async.get());
    }
/**
true	complete
*/

对结果进行处理

thenApply()


    public static void api2() {
        /**
         * thenApply可以带者参数继续执行,遇到异常停止
         */
        CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("111");
            return 1;
        }, Executors.newFixedThreadPool(3)).thenApply(f -> {
            System.out.println("222");
            return f + 1;
        }).thenApply(f -> {
            System.out.println("333");
            return f + 1;
        }).whenComplete((v, e)->{
            if (e == null) {
                System.out.println("计算结果为:" + v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });
    }

111
222
333
计算结果为:3
public <U> CompletableFuture<U> handle(
    BiFunction<? super T, Throwable, ? extends U> fn)
    public static void api3() {
       /**
        * handle方法与thenApply类似,但是遇到异常仍可以执行
        * thenApply可以带者参数继续执行
        */
       CompletableFuture.supplyAsync(()->{
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println("111");
           return 1;
       }, Executors.newFixedThreadPool(3)).handle((f, e) -> {
           int i = 10 / 0;
           System.out.println("222");
           return f + 1;
       }).handle((f, e) -> {
           System.out.println("333");
           return f + 1;
       }).whenComplete((v, e)->{
           if (e == null) {
               System.out.println("计算结果为:" + v);
           }
       }).exceptionally(e->{
           e.printStackTrace();
           System.out.println(e.getMessage());
           return null;
       });
   }
111
333
java.lang.NullPointerException

对结果进行消费

thenRun(Runnable runnable) 任务A执行完执行B,并且B不需要A的结果
thenAccept(Consumer action) 任务A执行完执行B,B需要A的结果,但是任务B无返回值
thenApply(Function fn)任务A执行完执行B,B需要A的结果,但是任务B有返回值

 public static void api4() {
       System.out.println(CompletableFuture.supplyAsync(()->"result").thenRun(()->{}).join());
       System.out.println(CompletableFuture.supplyAsync(()->"result").thenAccept(r-> System.out.println(r)).join());
       System.out.println(CompletableFuture.supplyAsync(()->"result").thenApply(r-> r + "resultB").join());
   }
执行结果
null
result
null
resultresultB

对计算速度进行选用

applyToEither()

    public static void api5() throws ExecutionException, InterruptedException {
        CompletableFuture<String> a_come_in = CompletableFuture.supplyAsync(() -> {
            System.out.println("A come in");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playA";
        });

        CompletableFuture<String> b_come_in = CompletableFuture.supplyAsync(() -> {
            System.out.println(" come in");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playB";
        });

        CompletableFuture<String> result = a_come_in.applyToEither(b_come_in, f -> {
            return f + " is winner";
        });

        System.out.println(result.get());

    }

对计算结果进行合并

thenCombine
两个CompletionStage任务都完成后,最终能把两个任务的结果一起交给thenCombine来处理
先完成的先等着,等待其它分支任务

public static void api6() throws ExecutionException, InterruptedException {
        CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> {

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "A";
        });

        CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "B";
        });

        CompletableFuture<String> result = a.thenCombine(b, (x, y) -> {
            System.out.println("两个结果合并");
            return x + y;
        });

        System.out.println(result.get());

    }

执行结果
两个结果合并
AB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值