java juc之CompletableFuture

supplyAsync/runAsync 开启任务
thenComposeAsync 连接任务
thenCombineAsync 合并任务

一、创建异步任务

    @Test
    public void test4() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        //supplyAsync 相当于ExecutorService submit方法
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            return "supplyAsync";
        }, executorService);
        System.out.println(future1.get());

        //相runAsync 相当于ExecutorService execute方法
        CompletableFuture.runAsync(()->{
            System.out.println("runAsync");
        }, executorService);

        //简单玩玩
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            String a = "ab";

            CompletableFuture<String> future4 = CompletableFuture.supplyAsync(() -> {
                return "c";
            },executorService);
            return a+future4.join();
        }, executorService);
        
        System.out.println(future3.get());
    }

二、简单入门

    @Test
    public void test5() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        //thenApply 执行第一个任务后 把返回值交给第二个任务执行 两个任务是同一线程
        //注意以下的XXXX和XXXXAsync都是一个意思
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "abcd";
        }, executorService).thenApply((String s)->{
            return s+"1234";
        });
        System.out.println(future2.get());

        //thenApplyAsync 执行第一个任务后 把返回值交给第二个任务执行 两个任务可能不是同一线程
        //注意以下的XXXX和XXXXAsync都是一个意思
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            return "abcd";
        }, executorService).thenApplyAsync((String s)->{

            return s+"1234";
        }, executorService);
        System.out.println(future3.get());

        //thenAccept 接收上一个任务的返回值作为参数,方法 无返回值
        CompletableFuture.supplyAsync(() -> {
            return "thenAccept";
        }, executorService).thenAccept((String s)->{
            System.out.println(s);
        });

        //thenRun 第一个任务后执行下一个方法 方法没有入参 也没有返回值
        CompletableFuture.runAsync(() -> {
            System.out.println("thenRun");
        }, executorService).thenRun(()->{
            System.out.println("runRunRun");
        });

        //thenCompose 把前一个任务的执行结果交给下一个任务
        CompletableFuture<Integer> future33 = CompletableFuture.supplyAsync(() -> {
            return 5;
        }, executorService).thenComposeAsync((num)->{
            return CompletableFuture.supplyAsync(()->{
                return num+4;
            }, executorService);
        }, executorService);
        System.out.println("future33="+future33.join());

        //exceptionally没问题就正常返回 有问题就返回exceptionally的返回值
        CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
            int i= 1/1; //int i= 1/1;
            return 10;
        }).exceptionally(ex -> {
            System.out.println("输出异常"+ex.getMessage());
            return -1;
        });
        System.out.println(future4.get());

        //whenComplete第一个是执行结果  第二个是异常 方法无返回值
        CompletableFuture<Integer> future5 = CompletableFuture.supplyAsync(() -> {
            int i= 1/1; //int i= 1/1;
            return 580;
        }).whenComplete((res,ex)->{
            if(ex!=null){
                System.out.println("异常了 返回结果是"+ex.getMessage());
            }else{
                System.out.println("正常执行 返回结果是"+res);
            }
        });
        System.out.println(future5.get());

        //handle第一个是执行结果  第二个是异常 方法有返回值
        CompletableFuture<Integer> future6 = CompletableFuture.supplyAsync(() -> {
            int i= 1/0; //int i= 1/1;
            return 580;
        }).handle((res,ex)->{
            if(ex!=null){
                System.out.println("异常了 是"+ex.getMessage());
            }else{
                System.out.println("正常执行 是"+res);
            }
            return 789;
        });
        System.out.println(future6.get());

        //thenCombine / thenAcceptBoth / runAfterBoth
        //这三个方法都是将两个CompletableFuture组合起来,只有这两个都正常执行完了才会执行某个任务
        //thenCombine会将两个任务的执行结果作为方法入参传递到指定方法中,且该方法有返回值
        //thenAcceptBoth同样将两个任务的执行结果作为方法入参,但是无返回值 【不做演示】
        //runAfterBoth没有入参,也没有返回值 【不做演示】
        CompletableFuture<Integer> future7 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        }, executorService);

        CompletableFuture<Integer> future8 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        }, executorService);

        long startTime=System.currentTimeMillis();

        CompletableFuture<Integer> future9 = future7.thenCombineAsync(future8,(a,b)->{
            System.out.println(Thread.currentThread()+" future9时间->"+System.currentTimeMillis());
            return a+b;
        },executorService);

        System.out.println(Thread.currentThread()+" main线程时间->"+System.currentTimeMillis());
        //计算结果花费的时间为10s
        System.out.println(future9.get());

        //这三个方法都是将两个CompletableFuture组合起来,只要其中一个执行完了就会执行某个任务
        //applyToEither会将已经执行完成的任务的执行结果作为方法入参,并有返回值
        //acceptEither同样将已经执行完成的任务的执行结果作为方法入参,但是没有返回值;
        //runAfterEither没有方法入参,也没有返回值。
        CompletableFuture<String> future10 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "我10s";
        }, executorService);

        CompletableFuture<String> future11 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "哈哈我5s";
        }, executorService);

        CompletableFuture<String> future12 = future11.applyToEitherAsync(future10, (s)->{
            return s;
        }, executorService);
        //永远只返回 哈哈我5s 而我10s永远不会返回了
        System.out.println(future12.get());

        //allOf返回的CompletableFuture是多个任务都执行完成后才会执行
        //只有有一个任务执行异常,则返回的CompletableFuture执行get方法时会抛出异常,如果都是正常执行,则get返回nul
        CompletableFuture<Void> future13 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future13");
        }, executorService);

        CompletableFuture<Void> future14 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future14");
        }, executorService);

        CompletableFuture<Void> future15 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future15");
        }, executorService);

        CompletableFuture<Void> of = CompletableFuture.allOf(future13, future14, future15);
        System.out.println(of.get());

        CompletableFuture<Void> future16 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future16");
        }, executorService);

        CompletableFuture<Void> future17 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future17");
        }, executorService);

        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future16, future17);
        System.out.println(anyOf.join());
    }

你可能感兴趣的:(java本身,java)