Java CompletableFuture组合拼装异步线程任务(2)
  TEZNKK3IfmPf 2023年11月14日 45 0

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
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   23天前   50   0   0 java
  TEZNKK3IfmPf   2024年05月31日   55   0   0 java
TEZNKK3IfmPf