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

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/80669590