天天看點

多個CompletableFuture 串行執行

多個

CompletableFuture

可以串行執行

public class Main {

    public static void main(String[] args) throws Exception {

        // 第一個任務:

        CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(() -> {

            return queryCode("中國石油");

        });

        // cfQuery成功後繼續執行下一個任務:

        CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code) -> {

            return fetchPrice(code);

        });

        // cfFetch成功後列印結果:

        cfFetch.thenAccept((result) -> {

            System.out.println("price: " + result);

        });

        // 主線程不要立刻結束,否則CompletableFuture預設使用的線程池會立刻關閉:

        Thread.sleep(2000);

    }

    static String queryCode(String name) {

        try {

            Thread.sleep(100);

        } catch (InterruptedException e) {

        }

        return "601857";

    }

    static Double fetchPrice(String code) {

        try {

            Thread.sleep(100);

        } catch (InterruptedException e) {

        }

        return 5 + Math.random() * 20;

    }

}