zoukankan      html  css  js  c++  java
  • 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的刷盘和同步的线程模型。

  • 相关阅读:
    灾后重建
    ZYN砍树
    聪聪可可
    GirlCat
    图表控件== 百度 echarts的入门学习
    图表控件的学习===》hightChart 和 Chartjs的使用
    拆分订单===初
    net 的单元测试 初学
    vue js 用nodejs的依赖包 --2016-08-23
    后台框架--HUI 的学习跟使用1
  • 原文地址:https://www.cnblogs.com/gaojy/p/15090147.html
Copyright © 2011-2022 走看看