JDK1.8 CompletableFuture特性介绍

 CompletableFuture实现了Future和CompletionStage两个接口,CompletionStage可以看做是一个异步任务执行过程的抽象。我们可以基于CompletableFuture方便的创建任务和链式处理多个任务。下面我们通过实例来介绍它的用法。

 

1.异步无返回

CompletableFuture<Void> futureAsync = CompletableFuture.runAsync(() -> { 
    System.out.println("业务代码");
});

2.异步有返回

CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
      //业务代码
    return T;
});

3.引入线程池

ExecutorService exector = Executors.newFixedThreadPool(10);
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
    // 业务代码
    return T;
}, executor);

4.阻塞拿结果

CompletableFuture.get()

5.异步拿结果

CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
    // 业务代码
    return T;
});

future.whenComplete((result, exception) -> {
    if (null == exception) {
       //正常结果
    } else{ 
        //有异常
    }
});

6.异常与结果分开处理,可单独处理结果或异常

CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("error");
}).exceptionally(ex -> {
    //异常信息处理
    return ex.getMessage();
}).thenAccept(result -> {
    //结果处理
});

7.子线程之间需依赖结果传递

CompletableFuture.supplyAsync(() -> {
    return "result1";
}).thenApply(previousResult -> {
    return previousResult + " result2";
}).thenApply(previousResult -> {
    return previousResult + " result3";
}).thenAccept(previousResult -> {
    System.out.println(previousResult);
});

控制台打印如下:
result1 result2 result3

8.嵌套调用

CompletableFuture<CompletableFuture<T>> res = method1().thenApply(result1 -> {
    return method2(result1);
});

 

9.组合调用

CompletableFuture<T> res = method1().thenCompose(result1 -> {
    return method2(result1);
});

 

10.多线程并行处理

     10.1收集子线程

List<CompletableFuture> cfList = new ArrayList<CompletableFuture>();

 for (int i = 0; i < 业务集合; i++) {                       
         CompletableFuture<T> cf = CompletableFuture.supplyAsync(() -> {
                           
                  return customMethod();
         }, executor);

          cfList.add(cf);               
}

      10.2 统一控制所有子线程

    CompletableFuture<Void> allFutures =
        CompletableFuture
            .allOf(cfList.toArray(new CompletableFuture[cfList.size()]));

    10.3 阻塞所有子线程

allFutures .get()

     10.4异步获取所有子线程结果

    CompletableFuture<List<T>> allChildCfResultList= allFutures.thenApply(v -> {
        return cfList.stream().map(cf-> cf.join())
            .collect(Collectors.toList());
    });

   10.5 任意子线程结束即返回结果

CompletableFuture<T> anyOfFutures = CompletableFuture.anyOf(cf1, cf2, cf3);

该文章参考网址:http://www.mamicode.com/info-detail-2204348.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值