CompletableFuture使用Demo

1.code

public void testCompletableFuture(){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        //1、使用runAsync或supplyAsync发起异步调用
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            return "result1";
        }, executor);
        //2、CompletableFuture.completedFuture()直接创建一个已完成状态的CompletableFuture
        CompletableFuture<String> cf2 = CompletableFuture.completedFuture("result2");
        //3、先初始化一个未完成的CompletableFuture,然后通过complete()、completeExceptionally(),完成该CompletableFuture
        CompletableFuture<String> cf = new CompletableFuture<>();
        cf.complete("success");

        //4.一元依赖:依赖一个CF cf3依赖cf1    cf5依赖cf2
        CompletableFuture<String> cf3 = cf1.thenApply(result1 -> {
            //result1为CF1的结果
            //......
            return "result3";
        });
        CompletableFuture<String> cf5 = cf2.thenApply(result2 -> {
            //result2为CF2的结果
            //......
            return "result5";
        });

        //5.二元依赖:依赖两个CF  cf4同时依赖cf1 cf2
        CompletableFuture<String> cf4 = cf1.thenCombine(cf2, (result1, result2) -> {
            //result1和result2分别为cf1和cf2的结果
            return "result4";
        });

        //6.多元依赖:依赖多个CF
        CompletableFuture<Void> cf6 = CompletableFuture.allOf(cf3, cf4, cf5);
        CompletableFuture<String> result = cf6.thenApply(v -> {
            //这里的join并不会阻塞,因为传给thenApply的函数是在CF3、CF4、CF5全部完成时,才会执行 。
            String result3 = cf3.join();
            String result4 = cf4.join();
            String result5 = cf5.join();
            //根据result3、result4、result5组装最终result;
            return "result";
        });


        //7.线程池异步处理
        ExecutorService threadPool1 = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(100));
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync 执行线程:" + Thread.currentThread().getName());
            //业务操作
            return "";
        }, threadPool1);
        //此时,如果future1中的业务操作已经执行完毕并返回,则该thenApply直接由当前main线程执行;否则,将会由执行以上业务操作的threadPool1中的线程执行。
        future1.thenApply(value -> {
            System.out.println("thenApply 执行线程:" + Thread.currentThread().getName());
            return value + "1";
        });
        //使用ForkJoinPool中的共用线程池CommonPool
        future1.thenApplyAsync(value -> {
            //do something
            return value + "1";
        });
        //使用指定线程池
        future1.thenApplyAsync(value -> {
            //do something
            return value + "1";
        }, threadPool1);



    }

    @FunctionalInterface
    public interface ThriftAsyncCall {
        void invoke() throws Exception;
    }

    public interface OctoThriftCallback<R, T> {
        void addObserver(OctoObserver<T> octoObserver);
    }

    public interface OctoObserver<T> {
        void onSuccess(T t);
        void onFailure(Throwable throwable );
    }
    /**
     * 该方法内部rpc注册监听的封装,可以作为其他实现的参照
     * OctoThriftCallback 为thrift回调方法
     * ThriftAsyncCall 为自定义函数,用来表示一次thrift调用(定义如上)
     */
    public static <T> CompletableFuture<T> toCompletableFuture(final OctoThriftCallback<?,T> callback , ThriftAsyncCall thriftCall) {
        //新建一个未完成的CompletableFuture
        CompletableFuture<T> resultFuture = new CompletableFuture<>();
        //监听回调的完成,并且与CompletableFuture同步状态
        callback.addObserver(new OctoObserver<T>() {
            @Override
            public void onSuccess(T t) {
                resultFuture.complete(t);
            }
            @Override
            public void onFailure(Throwable throwable) {
                resultFuture.completeExceptionally(throwable);
            }
        });
        if (thriftCall != null) {
            try {
                thriftCall.invoke();
            } catch (Exception e) {
                resultFuture.completeExceptionally(e);
            }
        }
        return resultFuture;
    }

 

posted @ 2022-08-03 15:45  A小小高  阅读(298)  评论(0编辑  收藏  举报