介绍

JDK1.8引入CompletableFuture类。

使用方法


public class CompletableFutureTest { private static ExecutorService threadPool = new ThreadPoolExecutor(40, 100,
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(20)); public String B() {
System.out.println("执行方法B");
sleep(5);
return "Function B";
} public String C() {
System.out.println("执行方法C");
sleep(20);
return "Function C";
} public void sleep(int i) {
try {
Thread.sleep(i * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} public void testCompableFuture() {
CompletableFuture<String> future;
try {
//Returns a new CompletableFuture
// that is asynchronously completed by a task running in the given executor
// with the value obtained by calling the given Supplier.
future = CompletableFuture.supplyAsync(() -> B(), threadPool);
//若去掉线程池,有何区别future = CompletableFuture.supplyAsync(() -> B()); sleep(9);
System.out.println(future.toString());
System.out.println(future.isDone());
} catch (RejectedExecutionException e) {
System.out.println("调用搜索列表服务线程满负荷, param:{}");
}
} public static void main(String[] args) {
CompletableFutureTest test = new CompletableFutureTest();
test.testCompableFuture();
} }

API

supplyAsync方法

JDK方法描述

/**
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the given executor with the value obtained
* by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param executor the executor to use for asynchronous execution
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}

应用场景

请求A的执行方法X,需满足下列需求:

①请求B、C、D中任一一个请求有返回结果,则X方法返回响应结果。

②请求B、C、D中都执行完,则X方法返回响应结果。

源码阅读

依赖关系

参考文档

JDK API文档

20 个使用 Java CompletableFuture的例子

最新文章

  1. iframe用法
  2. Cesium简介以及离线部署运行
  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(18)-权限管理系统-表数据
  4. EF和MVC系列文章导航:EF Code First、DbContext、MVC
  5. contiki-定时器etimer
  6. algorithm -- 选择排序
  7. 常用vs快捷键
  8. js动态加载css文件和js文件的方法
  9. ReSharper 8.XXX 注册机
  10. 如何&quot;格式化&quot;用过的磁带,让他被新磁带机重复利用
  11. tcp/udp socket编程异同
  12. Redis的简单使用和介绍
  13. Centos7+lnmp+zabbix4+分离mysql实验
  14. 2019春第九周作业Compile Summarize
  15. Sublime Text3 调色板 ColorPicker插件安装及快捷键
  16. Hbase的集群安装
  17. myclipse里有感叹号的问题,希望可以帮到各位
  18. android设置透明度代码片段
  19. win10ssh连接ubuntu服务器并本地绘图
  20. 无法启动MYSQL服务”1067 进程意外终止”解决的方法

热门文章

  1. 基于【 springBoot +springCloud+vue 项目】一 || 项目架构简介
  2. Map和TreeMap的特点
  3. win10 系统解决mysql中文乱码问题
  4. js几种数组排序及sort的实现
  5. springboot系列(六) 使用模板引擎
  6. Django组件之modelform
  7. [ansible-playbook]4 持续集成环境之分布式部署利器 ansible playbook学习
  8. java后端处理高并发
  9. frp服务搭建
  10. Python笔记(30)-----logger