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",我在无意中发现了它们所具有的相同的一些用法,先举 ...
随机推荐
- Hadoop系列001-大数据概论
本人微信公众号,欢迎扫码关注! 大数据概论 1.大数据概念 大数据(big data),指无法在一定时间范围内用常规软件工具进行捕捉.管理和处理的数据集合,是需要新处理模式才能具有更强的决策力.洞察发 ...
- mongo connections url string 的问题
摘要 driver 连接Mongo DB的url其实很简单,就是几个变量拼接成一个url,和关系型数据库没什么不同.但是因为mongo有单个instance和replicaSet不同的部署策略,还有m ...
- 【机器学习】--FP-groupth算法从初始到应用
一.前述 二.构建FP_groupth数流程 1.扫描事务数据库D 一次.收集频繁项的集合F 和它们的支持度.对F 按支持度降序排序,结果为频繁项表L. 2.创建FP 树的根节点,以“null”标记它 ...
- Spring之旅第四篇-注解配置详解
一.引言 最近因为找工作,导致很长时间没有更新,找工作的时候你会明白浪费的时间后面都是要还的,现在的每一点努力,将来也会给你回报的,但行好事,莫问前程!努力总不会有错的. 上一篇Spring的配置博客 ...
- 如何将Azure DevOps中的代码发布到Azure App Service中
标题:如何将Azure DevOps中的代码发布到Azure App Service中 作者:Lamond Lu 背景 最近做了几个项目一直在用Azure DevOps和Azure App Servi ...
- springboot~Integer和int如何选择,Integer的意义何在
今天说一下自己在项目中遇到的问题,然后总结一下Integer引用类型和int值类型 关于默认值 Integer默认为null int默认为0 为什么把数据实体设计成Integer或者不是int 大叔认 ...
- 深度解密Go语言之Slice
目录 当我们在说 slice 时,到底在说什么 slice 的创建 直接声明 字面量 make 截取 slice 和数组的区别在哪 append 到底做了什么 为什么 nil slice 可以直接 a ...
- 【微信小程序项目实践总结】30分钟从陌生到熟悉
前言 我们之前对小程序做了基本学习: 1. 微信小程序开发07-列表页面怎么做 2. 微信小程序开发06-一个业务页面的完成 3. 微信小程序开发05-日历组件的实现 4. 微信小程序开发04-打造自 ...
- 【憩园】C#并发编程之异步编程(三)
写在前面 本篇是异步编程系列的第三篇,本来计划第三篇的内容是介绍异步编程中常用的几个方法,但是前两篇写出来后,身边的朋友总是会有其他问题,所以决定再续写一篇,作为异步编程(一)和异步编程(二)的补 ...
- WPR003N变成尸体的后记
这是一个很悲哀的标题,尽管本来不想说还是打算写出来. 应小便的要求本文不加任何字体变化,不设置玄关来等大家破解,只是很自然的把悲剧和大家分享一下. 自上回2019 Valentine's Day 圣地 ...