Java 多線程 回調地獄解決方式

利用completableFuture 事件回調解決
public static void main(String[] args) throws InterruptedException {
    long l = System.currentTimeMillis();
    CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
        try {
            System.out.println("在回調中執行耗時操作...");
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
        }

        return 100;
    });
    completableFuture = completableFuture.thenCompose(i -> {
        return CompletableFuture.supplyAsync(() -> {
            try{
            System.out.println("在回調的回調中執行耗時操作...");
            Thread.sleep(10000);
            }catch (Exception e){
                e.printStackTrace();
            }
            return i + 100;
        });
    });
    completableFuture.whenComplete((result, e) -> {
        System.out.println("計算結果:" + result);
    });
    System.out.println("主線程運算耗時:" + (System.currentTimeMillis() - l) + " ms");
    new CountDownLatch(1).await();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章