Java CompletableFuture组合拼装异步线程任务(2)

Java CompletableFuture组合拼装异步线程任务

 private void seq() throws ExecutionException, InterruptedException {
        System.out.println("时间1:" + System.currentTimeMillis());
        CompletableFuture<String> f1 = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return "2018";
            }
        });

        System.out.println("时间2:" + System.currentTimeMillis());
        CompletableFuture<Integer> f2 = f1.thenApply(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return Integer.parseInt(s);
            }
        });

        System.out.println("时间3:" + System.currentTimeMillis());
        CompletableFuture<Double> f3 = f2.thenApply(new Function<Integer, Double>() {
            @Override
            public Double apply(Integer i) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return (double) i;
            }
        });

        System.out.println("时间4:" + System.currentTimeMillis());
        f3.whenComplete((v, a) -> {
            System.out.println("v: " + v);
            System.out.println("a: " + a);
        });
        System.out.println("时间5:" + System.currentTimeMillis());
        System.out.println(f3.get());
        System.out.println("时间6:" + System.currentTimeMillis());
    }

输出结果:

06-12 18:49:08.337 6047-6047/zhangphil.test I/System.out: 时间1:1528800548337
06-12 18:49:08.339 6047-6047/zhangphil.test I/System.out: 时间2:1528800548339
06-12 18:49:08.340 6047-6047/zhangphil.test I/System.out: 时间3:1528800548340
06-12 18:49:08.341 6047-6047/zhangphil.test I/System.out: 时间4:1528800548341
06-12 18:49:08.342 6047-6047/zhangphil.test I/System.out: 时间5:1528800548342
06-12 18:49:17.347 6047-6089/zhangphil.test I/System.out: v: 2018.0
    a: null
06-12 18:49:17.347 6047-6047/zhangphil.test I/System.out: 2018.0
06-12 18:49:17.348 6047-6047/zhangphil.test I/System.out: 时间6:1528800557348

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值