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

  • 相关阅读:
    java类加载机制
    java反射
    java注解
    设计模式 单例模式
    #1015 : KMP算法
    idea 快捷键
    基础数据类型综合
    工厂模式 VS 策略模式
    AtomicI 多线程中的原子操作
    ThreadLocal<T>
  • 原文地址:https://www.cnblogs.com/gaojy/p/15090147.html
Copyright © 2011-2022 走看看