1. 程式人生 > >Java CompletableFuture組合拼裝非同步執行緒任務(2)

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