Java8新特性CompletableFuture

Java8新特性CompletableFuture

详细API示例

参考:https://www.cnblogs.com/laomumu/p/12386971.html

 

示例:

flushOKFuture3 是处理了flushOKFuture1  和 flushOKFuture2的结果,当 flushOKFuture3 完成以后,执行apply后面的任务。
public class CompleateFutureTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        method();
    }

    private static void method() throws ExecutionException, InterruptedException, ExecutionException {
        CompletableFuture<String> flushOKFuture1 = new CompletableFuture<>();
        CompletableFuture<String> flushOKFuture2 = new CompletableFuture<>();
        // thenCombine 会把 两个 CompletionStage 的任务都执行完成后,把两个任务的结果一块交给 thenCombine 来处理。
        CompletableFuture<String> flushOKFuture3 = flushOKFuture1.thenCombine(flushOKFuture2, (a, b) -> {

            return a + b + "======ab=========";
        });
        CompletableFuture<String> flushOKFuture4 = flushOKFuture3.thenApply(new Function<String, String>() {
            @Override
            public String apply(String t) {
                String result = t + "*********";
                // System.out.println("result2=" + result);
                return "result2=" + result;
            }
        });

        //假设线程1执行下面的代码
        flushOKFuture1.complete("flushOKFuture1 completed");
        //假设线程2执行下面的代码
        flushOKFuture2.complete("flushOKFuture2 completed");

        // 此时主线程才会返回  不然一直堵塞
        System.out.println(flushOKFuture3.get());  // flushOKFuture1 completedflushOKFuture2 completed======ab=========
        System.out.println(flushOKFuture4.get());  // result2=flushOKFuture1 completedflushOKFuture2 completed======ab=========*********

    }

}

这个模型是处理rocketmq的刷盘和同步的线程模型。

posted @ 2021-08-02 16:32  gaojy  阅读(155)  评论(0编辑  收藏  举报