天天看點

CompletableFuture的thenCombineAsync

CompletableFuture的thenCombineAsync

代碼:

private void test() {
    System.out.println("開始...");

    CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("傳回 zhang");
            return "zhang";
        }
    }).thenCombineAsync(CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("傳回 phil");
            return "phil";
        }
    }), new BiFunction<String, String, Object>() {
        @Override
        public Object apply(String s1, String s2) {
            String s = s1 + " , " + s2;
            System.out.println("apply:" + s);
            return s;
        }
    }).whenCompleteAsync(new BiConsumer<Object, Throwable>() {
        @Override
        public void accept(Object o, Throwable throwable) {
            System.out.println("accept:" + o.toString());
        }
    });

    System.out.println("運作至此.");
}      

運作輸出:

07-10 16:12:37.230 29410-29410/zhangphil.test I/System.out: 開始...

07-10 16:12:37.235 29410-29410/zhangphil.test I/System.out: 運作至此.

07-10 16:12:38.234 29410-29450/zhangphil.test I/System.out: 傳回 zhang

07-10 16:12:40.236 29410-29451/zhangphil.test I/System.out: 傳回 phil

07-10 16:12:40.237 29410-29451/zhangphil.test I/System.out: apply:zhang , phil

07-10 16:12:40.237 29410-29450/zhangphil.test I/System.out: accept:zhang , phil

繼續閱讀