CompletableFuture学习

CompleteFuture学习

package com.example.CompleteFutureTest;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * completeFuture用法
 */
public class Test {

    public static void main(String[] args) throws InterruptedException {
         
        //异步运行不带结果
        CompletableFuture<Void> cf0 = CompletableFuture.runAsync(()->{
            System.out.println("cf0运行结果: 你好"); 
        });  
      
        //异步运行带结果
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(()->{
            return "cf1运行结果: 你好";
        });
        try {
            System.out.println(cf1.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }

        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(()->{

            return "小猫";
        });

        CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(()->{

            return "小狗";
        });

        /*
          thenCombine 将两个异步运行的结果进行后续处理
         */
        CompletableFuture<String> cf4 = cf3.thenCombine(cf2,(a,b)->{

            return a+","+b;
        });

        //all of 多个CompletableFuture并行运行,除此之外还有个any of
        CompletableFuture<Void> cf5 = CompletableFuture.allOf(cf3,cf4);

        Thread.sleep(3000L);
        /*
          thenApply和handle都是对结果进行处理 区别在于前面的执行出现异常,apply不会继续处理,而handle会
         */
        CompletableFuture<String> cf6 = cf4.thenApply(res->{
            return res+" ,该吃饭了";
        }).thenApply(f->{
            return f+",再不吃饭就挨打";
        }).whenComplete((res,e)->{
            //不用get是因为get搞不好会阻塞
            System.out.println("结果: "+res);
            System.out.println("报错异常: "+e);
        }).exceptionally(e->{
          //异常处理 报异常才来到这里
            e.printStackTrace();
            System.out.println("出现异常,处理");
            return null;
        });


    }

}
posted @ 2024-05-14 13:53  Liang2003  阅读(2)  评论(0编辑  收藏  举报