CompletableFuture 异步编排的简单入门

使用前提方便于理解:
方法以下列方式开头:
run:无返回无感知(不接受参数)
accept:有感知(接受参数),无返回
apply:有感知,有返回
方法以下列方式结尾:
“async:”可以使用另一套线程组
不带则共享一套线程组

第一步:创建线程池

  public static ThreadFactory threadPoolExecutor = new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build();
    public static ExecutorService executor = new ThreadPoolExecutor(
            10,
            10,
            10L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(1024),
            threadPoolExecutor,
            new ThreadPoolExecutor.AbortPolicy());
            

方法比较:
1.runAsync()和 supplyAsync()

  public static void runAsSync(){
        CompletableFuture.runAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread());
            int i = 10/2;
            System.out.println("运行结果" + i);
        },executor);
    }
 public static void supplierAsSync(){
        CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread());
            int i = 10/2;
            System.out.println("运行结果" + i);
            return i;
        },executor);
    }

runAsync()不带返回值。 supplyAsync()带返回值

2.whenComplete()whenCompleteAsync()exceptionally()

// 无法影响返回结果,除非出异常
    public static Integer supplerAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread());
            int i = 10 / 0;
            System.out.println("运行结果" + i);
            return i;
        }, executor);

        future.whenComplete((res,exception) -> {
            System.out.println(String.format("异步成功完成了...结果是%d",res));
            System.out.println(String.format("异步成功完成了...异常是%d",exception));
        }).exceptionally(throwable -> {
            System.out.println(String.format("出现异常返回了"));
            return 100;
        });

        //Integer integer = future.get();
        //
        return 1;
    }

whenComplete():与whenCompleteAsync()的区别只在于是否添加别的线程组executor参数。方法完成时运行,且不能自定义返回值
exceptionally(): 出异常时可以自定义返回值

3.handle()自定义返回值

  /**
     * 感知结果 方法完成后处理
     */
    public static Integer supplerAsyncHandler() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread());
            int i = 10 / 2;
            System.out.println("运行结果" + i);
            return i;
        }, executor).handle((res,exception) -> {
            if(res != null){
                return res / 2;
            }
            if (exception != null){
                return 0;
            }
            return 0;
        });

        return future.get();
    }

handle():可以对执行返回的结果进行进一步处理并返回自定义值

4.thenRun() thenAccept() thenApply()

/**
     * 串行化
     * 1)thenRun 不能获取上一步执行结果
     * 2)thenAccept 能接受上一步结果,无返回值
     * @return
     */
    public static Integer supplerAsyncThenRun() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread());
            int i = 10 / 2;
            System.out.println("运行结果" + i);
            return i;
        }, executor)
             /*   // 表示不接受前者值直接运行下一个任务
                .thenRun(() ->{
                    System.out.println("任务2启动了");
                });*/
            /* .thenAccept(res ->{
                 System.out.println("任务2启动了"+res);
             });*/
            .thenApply((res) -> {
               return res / 5;
            });
        return future.get();
    }

6. runAfterBothAsync()thenAcceptBoth() thenCombineAsync() 将两个任務合并

 // 无法感知前两个结果,无返回值
        future1.runAfterBothAsync(future2,() -> {
            System.out.println("runAfterBothAsync()任务3开始");
            System.out.println("--------华丽分分割线-----------");
        },executor);



        // 感知两个结果,无返回值
        future1.thenAcceptBoth(future2,(res1,res2) -> {
            System.out.println("thenAcceptBoth()任务三。。。之前结果"+res1 +"-----"+res2);
            System.out.println("--------华丽分分割线-----------");
        });

        // 感知两个结果集并处理返回值
        CompletableFuture<String> stringCompletableFuture = future1.thenCombineAsync(future2, (res1, res2) -> {
            //System.err.println(res1+"========> "+res2);
            String format = "thenCombineAsync()任务三返回值res1="+res1+",----res2="+res2;
            //System.out.println(format);
            return format;
        }, executor);

        System.err.println("stringCompletableFuture值"+ stringCompletableFuture.get());

future1:任务一
future2:任务二

7.runAfterEither() acceptEither()applyToEither()两个任务只要有一个完成就执行任务三

 // 二者有一个执行成就成功
        // 不感知结果,无返回值
        future1.runAfterEither(future2,() -> {
            System.out.println("runAfterEither任务三执行");
            System.out.println("--------华丽分分割线-----------");
        });

        // 相同返回类型的,感知结果,无返回值
        future1.acceptEither(future2,(res) -> {
            System.out.println("acceptEither任务三执行"+ res);
            System.out.println("--------华丽分分割线-----------");
        });

        // 感知结果,有参有返回
        future1.applyToEither(future2,(res) -> {
            System.out.println("applyToEither"+ res);
            System.out.println("--------华丽分分割线-----------");
            return res.toString()+"applyToEither";
        });

加后缀async无非多加一个参数:线程池

8.allof() 多任务组合 全部返回才结束get()方法会阻塞等待

 CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2);
        allOf.get();

9.anyof() 任意任务完成就返回

CompletableFuture<Void> allOf = CompletableFuture.anyof(future1, future2);
        allOf.get();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值