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