CompletableFuture常用方法

8 篇文章 0 订阅

目录

1.获得结果触发计算

2.对计算结果进行处理

        thenApply:

        handle:

3.对计算结果进行消费

         thenRun---thenAccept---thenApply之间的代码执行顺序

4.对计算速度进行选用

5.对计算结果进行合并


 

1.获得结果触发计算


public class ComplatebleFutureDemo03 {
    public static void main(String[] args) {
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "aaa";
        });
        //getNow  如果上一步还没有计算完成,立即返回bbb。没有计算完成的情况下,给个备胎值。
//        System.out.println(stringCompletableFuture.getNow("bbb"));

        //暂停500ms
        try {
            TimeUnit.MILLISECONDS.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打断计算立即获取complete中的值
        System.out.println(stringCompletableFuture.complete("complete") + "\t" + stringCompletableFuture.join());
    }
}

2.对计算结果进行处理

        thenApply:

                计算结果存在依赖关系,这两个线程串行化(上一步的运算结果可以传给下一步),当前步骤报错,不会往下执行。

        

 private static void thenApply() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("第一步");
            return 1;
            //f  上一步运行的结果也就是1  传递给下一步
        },threadPool).thenApply(f ->{
            //1+2 =3
            System.out.println("第二步");
            return f+2;
        }).thenApply(f ->{
            //3+3 =6
            System.out.println("第三步");
            return f+3;
        }).whenComplete((v,e) ->{
            if (e == null){
                System.out.println("无异常,计算结果是:"+v);
            }
        }).exceptionally(throwable -> {
            throwable.printStackTrace();
            System.out.println("有异常");
            System.out.println(throwable.getMessage());
            return null;
        });
        System.out.println(Thread.currentThread().getName()+"主线程去干其他事情");
        threadPool.shutdown();
    }

        handle:

                计算结果存在依赖关系,这两个线程串行化,当前步骤报错,可以继续往下走。

private static void handle() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() ->{
            try {TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("第一步");
            return 1;
        },threadPool).handle((f,e)->{
            int i = 10/0;
            System.out.println("第二步");
            return f+2;
        }).handle((f,e)->{
            System.out.println("第三步");
            return f+3;
        }).whenComplete((v,e)->{
            if (e==null){
                System.out.println("计算的值是:"+v);
            }
        }).exceptionally(throwable -> {
            throwable.printStackTrace();
            System.out.println(throwable.getMessage());
           return null;
        });
        System.out.println(Thread.currentThread().getName()+"主线程去干其他事情");
        threadPool.shutdown();
    }

3.对计算结果进行消费

        接收任务的处理结果,并消费处理,无返回结果。

    public static void main(String[] args) {
        //直接计算结果 无返回值
        CompletableFuture.supplyAsync(() -> {
            System.out.println("第一步");
            return 1;
        }).thenApply(f -> {
            System.out.println("第二步");
            return f + 2;
        }).thenApply(f -> {
            System.out.println("第三步");
            return f + 3;
        }).thenAccept(r -> {
            System.out.println("直接输出结果为:" + r);
        });
    }

         thenRun---thenAccept---thenApply之间的代码执行顺序

        

        //不需要上一步的返回结果 没有返回
        System.out.println(CompletableFuture.supplyAsync(() -> "resultA").thenRun(() -> {}).join());
        //需要上一步的结果,直接消费  无返回
        System.out.println(CompletableFuture.supplyAsync(() -> "resultA").thenAccept(System.out::println));
        //
        System.out.println(CompletableFuture.supplyAsync(() -> "resultA").thenApply(r -> (r + "resultB").toString()).join());

4.对计算速度进行选用

        哪个线程计算的速度快就返回哪个线程。

    public static void main(String[] args) {
        CompletableFuture<String> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("playA Come in");
            try {TimeUnit.MILLISECONDS.sleep(1500);} catch (InterruptedException e) {e.printStackTrace();}
            return "playA";
        });

        CompletableFuture<String> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("playB Come in");
            try {TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
            return "playB";
        });
        CompletableFuture<String> applyToEither = playA.applyToEither(playB, f -> {
            return f + " is win";
        });
        //哪个线程计算的快,就选择哪个线程返回
        System.out.println(Thread.currentThread().getName()+"-----"+ applyToEither.join());
    }

5.对计算结果进行合并

对多个线程的计算结果进行合并计算

    public static void main(String[] args) {
        CompletableFuture<Integer> integerCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " \t 开始");
            try {TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
            return 10;
        });

        CompletableFuture<Integer> integerCompletableFuture2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "开始");
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 20;
        });
        CompletableFuture<Integer> integerCompletableFuture = integerCompletableFuture1.thenCombine(integerCompletableFuture2, (x, y) -> {
            return x + y;
        });
        System.out.println("计算结果为:"+integerCompletableFuture.join());
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值