completable 用法
CompletableFuture
前面我们使用过jdk5 提出future的用法,但是在获取结果上并不是那么友好
在Java8中,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture 的方法。
没有用过的同学,我们先来一个入门使用了解一下
public class CompletableFutureAction {
private static final Random RANDOM = new Random(System.currentTimeMillis());
public static void main(String[] args) {
//很少有这么使用的.
CompletableFuture<Double> completableFuture = new CompletableFuture<>();
new Thread(()->{
double v = get();
completableFuture.complete(v);
}).start();
System.out.println("程序执行");
//当程序完成时自动回调,不需要阻塞
completableFuture.whenComplete((v,t)->{
Optional.ofNullable(v).ifPresent(System.out::println);
Optional.ofNullable(t).ifPresent(x->{t.printStackTrace();});
});
System.out.println("程序执行后...");
}
static double get(){
try {
System.out.println("执行耗时任务");
Thread.sleep(RANDOM.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return RANDOM.nextDouble();
}
}
CompletableFuture.supplyAsync
我们一般不使用new的方式创建completableFuture
在main 方法中我们在使用一个例子来介绍它的使用
因为在mian方法中,主线程可能会提前结束所以我们在做这个例子的时候,需要对线程做一些阻塞
public class CompletableFutureAction1 {
public static void main(String[] args) throws InterruptedException {
//另一种方式来等到结果输出在结束
ExecutorService executorService = Executors.newFixedThreadPool(2,r -> {
Thread t = new Thread(r);
//设置成守护线程->结果不一定能等到执行结束
t.setDaemon(false);
return t;
});
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
CompletableFuture.supplyAsync(CompletableFutureAction::get,executorService).whenComplete((v,t)->
{
Optional.of(v).ifPresent(System.out::println);
atomicBoolean.set(false);
executorService.shutdown();
Optional.ofNullable(t).ifPresent(x->{t.printStackTrace();});
});
System.out.println("没有进入阻塞");
// Thread.currentThread().join();
/* while (atomicBoolean.get()){
}*/
executorService.execute(()-> System.out.println("2222"));
}
}
我们可以使用这样的方式来判断获取到结果
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
CompletableFuture.supplyAsync(CompletableFutureAction::get).whenComplete((v,t)->
{
Optional.of(v).ifPresent(System.out::println);
atomicBoolean.set(false);
executorService.shutdown();
Optional.ofNullable(t).ifPresent(x->{t.printStackTrace();});
}); System.out.println("没有进入阻塞");
// Thread.currentThread().join();
while (atomicBoolean.get()){ }
comletableFuture流水线的工作
CompletableFuture.supplyAsync(CompletableFutureAction::get,executorService)
.thenApply(CompletableFutureAction2::multiply).whenComplete((v,t)->{
Optional.of(v).ifPresent(System.out::println);
// executorService.shutdown();
Optional.ofNullable(t).ifPresent(x->{t.printStackTrace();} ); });
public static double multiply(double value){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return value*10d;
}
static double get(){
try {
System.out.println("=======执行耗时任务");
Thread.sleep(RANDOM.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
double v = RANDOM.nextDouble();
System.out.println(v);
return v;
}
执行的结果:
=======执行耗时任务
没有进入阻塞
0.808110430680034
8.08110430680034
多任务调度方式模拟:
List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
Stream<CompletableFuture<Double>> completableFutureStream = ids.parallelStream().map(i -> CompletableFuture.supplyAsync(() -> queryByid(i), executorService));
//这边也是并行执行
List<Double> collect = completableFutureStream.map(future -> future.thenApply(CompletableFutureAction2::multiply)).map(CompletableFuture::join).collect(Collectors.toList());
System.out.println(collect);
public static double queryByid(double i){
return CompletableFutureAction.get();
}
comletableFuture API
completable 用法的更多相关文章
- EditText 基本用法
title: EditText 基本用法 tags: EditText,编辑框,输入框 --- EditText介绍: EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是 ...
- jquery插件的用法之cookie 插件
一.使用cookie 插件 插件官方网站下载地址:http://plugins.jquery.com/cookie/ cookie 插件的用法比较简单,直接粘贴下面代码示例: //生成一个cookie ...
- Java中的Socket的用法
Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...
- [转载]C#中MessageBox.Show用法以及VB.NET中MsgBox用法
一.C#中MessageBox.Show用法 MessageBox.Show (String) 显示具有指定文本的消息框. 由 .NET Compact Framework 支持. MessageBo ...
- python enumerate 用法
A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , whe ...
- [转载]Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结
本文对Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法进行了详细的总结,需要的朋友可以参考下,希望对大家有所帮助. 详细解读Jquery各Ajax函数: ...
- 【JavaScript】innerHTML、innerText和outerHTML的用法区别
用法: <div id="test"> <span style="color:red">test1</span> tes ...
- chattr用法
[root@localhost tmp]# umask 0022 一.chattr用法 1.创建空文件attrtest,然后删除,提示无法删除,因为有隐藏文件 [root@localhost tmp] ...
- 萌新笔记——vim命令“=”、“d”、“y”的用法(结合光标移动命令,一些场合会非常方便)
vim有许多命令,网上搜有一堆贴子.文章列举出各种功能的命令. 对于"="."d"."y",我在无意中发现了它们所具有的相同的一些用法,先举 ...
随机推荐
- 零基础java的福音!史上最全最精简的学习路线图!
这是一个java系统学习路线,从零基础到项目框架开发,每一个阶段里面内容都标记的很清楚,如果你现在也在学习java,你可以跟着这个系统学习路线学,学完自己可以独立的完成项目框架开发,二线城市拿个7k+ ...
- 解决 Mac launchpad 启动台 Gitter 图标无法删除的问题
Mac 删除应用非常简单,将应用拖到回收站就删除了.或者进入应用程序文件夹,选中程序,command + delete 就删除了应用,这也是删除文件的快捷键. 但是,安装 Gitter 后,删除了应用 ...
- 消费阿里云日志服务SLS
此文档只关心消费接入,不关心日志接入,只关心消费如何接入,可直接跳转到[sdk消费接入] SLS简介 日志服务: 日志服务(Log Service,简称 LOG)是针对日志类数据的一站式服务,在阿里巴 ...
- C++ 编程技巧笔记记录(持续更新)
C++是博大精深的语言,特性复杂得跟北京二环一样,继承乱得跟乱伦似的. 不过它仍然是我最熟悉且必须用在游戏开发上的语言,这篇文章用于挑选出一些个人觉得重要的条款/经验/技巧进行记录总结. 文章最后列出 ...
- Docker进阶之九:Dockerfile 及 通过Dockerfile搭建lnmp
一.Dockerfile指令 指令 描述 指令 描述 FROM 构建的新镜像是基于哪个镜像 例如:FROM centos:6 COPY 拷贝文件或目录到镜像,用法同上例如:COPY ./start.s ...
- 搞懂MySQL InnoDB B+树索引
一.InnoDB索引 InnoDB支持以下几种索引: B+树索引 全文索引 哈希索引 本文将着重介绍B+树索引.其他两个全文索引和哈希索引只是做简单介绍一笔带过. 哈希索引是自适应的,也就是说这个不能 ...
- c# 抽象类,抽象方法使用(abstract)
入行一年多,在这个IT行业,开发技术主要使用的是.NET,而对应使用的高级语言自然就是c#了.从2017年7月入职后,在平时的工作过程中,只记得使用一些方法去完成逻辑功能,而很少去深究一些语法特性,特 ...
- SpringMVC+Mybatis 如何配置多个数据源并切换?
最近公司一个项目需要连接两个数据库(A和B)操作,有的模块查询A库,有的模块查询B库,因此需要改造下,项目后台用的是SpringMVC+Mybatis+MySQL架构,折腾了两天后终于搞定了,在这里记 ...
- 一个简易的Python爬虫,将爬取到的数据写入txt文档中
代码如下: import requests import re import os #url url = "http://wiki.akbfun48.com/index.php?title= ...
- JavaScript 是如何工作的:JavaScript 的共享传递和按值传递
摘要: 原始数据类型和引用数据类型的副本作为参数传递给函数. 原文:JavaScript 是如何工作的:JavaScript 的共享传递和按值传递 作者:前端小智 Fundebug经授权转载,版权归原 ...