您现在的位置是:首页 > 文章详情

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

日期:2018-06-11点击:516

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

原文链接:https://yq.aliyun.com/articles/615645
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章