java8_CompletableFuture

CompletableFuture是java8新增加的类,可以实现线程编排,类似前端的promise

public class java8线程串行化 {
    public  static ExecutorService executors=Executors.newFixedThreadPool(10);
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        /* 一:
        * 0)supplyAsync有返回值
        * 1)runAsync无返回值
        * 2)whenComplete 能得到异常,但是无法修改
        * 3)exceptionally 出现异常返回默认值   能得到异常,可以修改
        * 4)handler方法 方法执行完成后的处理
        * */
        runAsync无返回值();

      CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("currentThread=" + Thread.currentThread().getId());
            int i = 10 / 2;
          // int i = 10 / 0;
            System.out.println("运行结果:" + i);
            return i;
        }, executors).whenComplete((res,exception)->{
            //能得到异常,但是无法修改
             System.out.println("异步任务完成了 ...结果是:"+res+";异常是:"+exception);
         }).exceptionally(exception->{
             //出现异常返回默认值   能得到异常,可以修改
             return 10;
         });
        Integer integer=future.get();
        System.out.println("有返回值="+integer);

        //handler方法 方法执行完成后的处理
        CompletableFuture<Integer> futureHandle = CompletableFuture.supplyAsync(() -> {
            System.out.println("currentThread=" + Thread.currentThread().getId());
            int i = 10 / 2;
            // int i = 10 / 0;
            System.out.println("运行结果:" + i);
            return i;
        }, executors).handle((res,exception)->{
            if(res!=null){
                return res*2;
            }
            if(exception!=null){
                return res*4;
            }
            return 0;
        });
        Integer in=futureHandle.get();
        System.out.println("有返回值="+integer);
        /*
            二:线程串行化
         * 1)thenRunAsync 无返回值
         * 2)thenAcceptAsync 能获取上一步的执行结果 无返回值
         * 3)thenApplyAsync 能获取上一步的执行结果 有返回值
         * */
       /* CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("currentThread=" + Thread.currentThread().getId());
            int i = 10 / 2;
            // int i = 10 / 0;
            System.out.println("运行结果:" + i);
            return i;
        }, executors).thenRunAsync(()->{
            System.out.println("任务2启动了");
        },executors);
        System.out.println("main end");
    */

       /* CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("currentThread=" + Thread.currentThread().getId());
            int i = 10 / 2;
            // int i = 10 / 0;
            System.out.println("运行结果:" + i);
            return i;
        }, executors).thenApplyAsync(res->{
            System.out.println("任务2启动了,接受上一步的返回值="+res);
            return "我有返回值"+res;
        }, executors);

        *//*.thenAcceptAsync(res->{
            System.out.println("任务2启动了,接受上一步的返回值="+res);
        },executors);*/

        //三:CompletableFuture-两任务组合-都要完成
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程=" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("任务1线程结束" );
            return i;
        }, executors);
        CompletableFuture<String> future2= CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程=" + Thread.currentThread().getId());
            System.out.println("任务2线程结束" );
            return "hello";
        }, executors);

        CompletableFuture<Integer> future22= CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程=" + Thread.currentThread().getId());

            try { //睡眠 模拟阻塞 延长任务执行时间
                Thread.sleep(3000);
                System.out.println("任务2线程结束" );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 8;
        }, executors);
        /*
        * runAfterBothAsync 任务 1 2 完成再执行任务3,无法得到返回值
        * thenAcceptBothAsync 任务 1 2 完成再执行任务3,可以得到返回值
        * thenCombineAsync 任务 1 2 完成再执行任务3,可以得到返回值 ,并处理结果
        * */

        /*future1.runAfterBothAsync(future2,()->{
            System.out.println("任务3开始");
                },executors);*/
        // //任务 1 2 完成再执行任务3,可以得到返回值
        future1.thenAcceptBothAsync(future2,(f1,f2)->{
            System.out.println("任务3开始,得到之前的结果"+f1+f2);
        },executors);

        //任务 1 2 完成再执行任务3,可以得到返回值 ,并处理结果
        CompletableFuture<String> future3= future1.thenCombineAsync(future2,(f1,f2)->{
           return "任务3开始,得到之前的结果"+f1+f2;
        },executors);
        System.out.println(future3.get());
        System.out.println("main end");

        //四:异步-CompletableFuture-两任务组合 有一个执行完就执行任务三
        /*
         * runAfterEitherAsync 不感知结果,自己没有返回值
         * acceptEitherAsync   感知结果 自己没有返回值
         * applyToEitherAsync    感知结果 自己有返回值
         * */
        future1.runAfterEitherAsync(future22,()->{
            System.out.println("任务3开始,前面任务有一个执行完就执行任务三");
        },executors);
        //void accept(T t);
        future1.acceptEitherAsync(future22,(res)->{
            System.out.println("任务3开始,前面要有相同的返回类型"+res);
        },executors);
        CompletableFuture<String> future33=  future1.applyToEitherAsync(future22,res->{
            System.out.println("任务3开始,前面要有相同的返回类型"+res);
            return res.toString()+"haha";
        },executors);

        System.out.println(future33.get());//最终结果);

      //  五:异步-CompletableFuture-多任务组合

        CompletableFuture<String> img=  CompletableFuture.supplyAsync(()->{
                System.out.println("查询商品图片信息");
                return "a.jpg";
            },executors);
        CompletableFuture<String> attr=  CompletableFuture.supplyAsync(()->{
            System.out.println("查询商品属性信息");
            return "黑色+256G";
        },executors);

        CompletableFuture<String> desc=  CompletableFuture.supplyAsync(()->{
            System.out.println("查询商品介绍信息");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "黑色+256G";
        },executors);

       // img.get();attr.get();desc.get(); 阻塞 挨个执行的
        CompletableFuture<Void> allOf=  CompletableFuture.allOf(img,attr,desc);
        allOf.join();//等待所有结果完成
        //五_1:  分别获得各个结果
        // System.out.println("main end"+img.get()+"==="+attr.get()+"=="+desc.get());
        //五_2:任意一个执行完成
        CompletableFuture<Object> anyOf=  CompletableFuture.anyOf(img,attr,desc);
        System.out.println("main end"+anyOf.get());

    }

    private static void runAsync无返回值() {
        CompletableFuture<Void> future=  CompletableFuture.runAsync(()->{
           System.out.println("currentThread="+Thread.currentThread().getId());
           int i=10/2;
           System.out.println("运行结果:"+i);
       } ,executors);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值