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的刷盘和同步的线程模型。

  • 相关阅读:
    c# Queue实现生产者(Producer)消费者(Consumer)模式
    无法连接到已配置的web服务器
    2018年新年计划
    md5加密、Des加密对称可逆加密、RSA非对称可逆加密、https单边验证、银行U盾双边认证
    通过HTTP协议实时获取微信聊天记录
    c#委托与事件
    c#异步多线程
    详细解读PHP时区修改正确方法
    Mysql分库分表方案
    关于Windows下安装mongodb和加入Windows系统启动项
  • 原文地址:https://www.cnblogs.com/gaojy/p/15090147.html
Copyright © 2011-2022 走看看