CompletableFuture多個異步任務並行獲取返回值實現

private static void man() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Man man = new Man();
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(CompletableFutureDemo::name, threadPool);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(CompletableFutureDemo::age, threadPool);
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(CompletableFutureDemo::sex, threadPool);

        CompletableFuture<Void> completableFuture1 = future1.thenAccept(man::setName);
        CompletableFuture<Void> completableFuture2 = future2.thenAccept(man::setAge);
        CompletableFuture<Void> completableFuture3 = future3.thenAccept(man::setSex);

        CompletableFuture<Void> completableFuture = CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3);
        completableFuture.join();
        System.out.println(man);
        threadPool.shutdown();
        System.out.println("耗時:"+(System.currentTimeMillis()-startTime)/1000+"s");
    }
private static String name(){
        try {
            Thread.sleep(6000);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return "ZZZ";
    }
    private static Integer age(){
        try {
            Thread.sleep(4000);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return 18;
    }
    private static String sex(){
        try {
            Thread.sleep(3000);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return "男";
    }

在這裏插入圖片描述
耗時爲最長的那個方法的時間,大大節省了時間

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章