thenApply(等待并转化future)

@Test

public void testThen() throws ExecutionException, InterruptedException {

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

return "zero";

}, executor);

CompletableFuture f2 = f1.thenApply(new Function() {

@Override

public Integer apply(String t) {

System.out.println(2);

return Integer.valueOf(t.length());

}

});

CompletableFuture f3 = f2.thenApply(r -> r * 2.0);

System.out.println(f3.get());

}

thenAccept与thenRun(监听future完成)

/**

* future完成处理,可获取结果

*/

@Test

public void testThenAccept(){

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

return "zero";

}, executor);

f1.thenAccept(e -> {

System.out.println("get result:"+e);

});

}

/**

* future完成处理

*/

@Test

public void testThenRun(){

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

return "zero";

}, executor);

f1.thenRun(new Runnable() {

@Override

public void run() {

System.out.println("finished");

}

});

}

thenCompose(flatMap future)

/**

* compose相当于flatMap,避免CompletableFuture>这种

* @throws ExecutionException

* @throws InterruptedException

*/

@Test

public void testThenCompose() throws ExecutionException, InterruptedException {

ExecutorService executor = Executors.newFixedThreadPool(5);

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

return "zero";

}, executor);

CompletableFuture> f4 = f1.thenApply(CompletableFutureTest::calculate);

System.out.println("f4.get:"+f4.get().get());

CompletableFuture f5 = f1.thenCompose(CompletableFutureTest::calculate);

System.out.println("f5.get:"+f5.get());

System.out.println(f1.get());

}

public static CompletableFuture calculate(String input) {

ExecutorService executor = Executors.newFixedThreadPool(5);

CompletableFuture future = CompletableFuture.supplyAsync(() -> {

System.out.println(input);

return input + "---" + input.length();

}, executor);

return future;

}

thenCombine与thenAcceptBoth

thenCombine(组合两个future,有返回值)

/**

* thenCombine用于组合两个并发的任务,产生新的future有返回值

* @throws ExecutionException

* @throws InterruptedException

*/

@Test

public void testThenCombine() throws ExecutionException, InterruptedException {

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f1 start to sleep at:"+System.currentTimeMillis());

Thread.sleep(1000);

System.out.println("f1 finish sleep at:"+System.currentTimeMillis());

} catch (InterruptedException e) {

e.printStackTrace();

}

return "zero";

}, executor);

CompletableFuture f2 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f2 start to sleep at:"+System.currentTimeMillis());

Thread.sleep(3000);

System.out.println("f2 finish sleep at:"+System.currentTimeMillis());

} catch (InterruptedException e) {

e.printStackTrace();

}

return "hello";

}, executor);

CompletableFuture reslutFuture =

f1.thenCombine(f2, new BiFunction() {

@Override

public String apply(String t, String u) {

System.out.println("f3 start to combine at:"+System.currentTimeMillis());

return t.concat(u);

}

});

System.out.println(reslutFuture.get());//zerohello

System.out.println("finish combine at:"+System.currentTimeMillis());

}

thenAcceptBoth(组合两个future,没有返回值)

/**

* thenAcceptBoth用于组合两个并发的任务,产生新的future没有返回值

* @throws ExecutionException

* @throws InterruptedException

*/

@Test

public void testThenAcceptBoth() throws ExecutionException, InterruptedException {

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f1 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(1);

System.out.println("f1 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "zero";

}, executor);

CompletableFuture f2 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f2 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(3);

System.out.println("f2 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "hello";

}, executor);

CompletableFuture reslutFuture = f1.thenAcceptBoth(f2, new BiConsumer() {

@Override

public void accept(String t, String u) {

System.out.println("f3 start to accept at:"+System.currentTimeMillis());

System.out.println(t + " over");

System.out.println(u + " over");

}

});

System.out.println(reslutFuture.get());

System.out.println("finish accept at:"+System.currentTimeMillis());

}

applyToEither与acceptEither

applyToEither(取2个future中最先返回的,有返回值)

/**

* 当任意一个CompletionStage 完成的时候,fn 会被执行,它的返回值会当做新的CompletableFuture的计算结果

* @throws ExecutionException

* @throws InterruptedException

*/

@Test

public void testApplyToEither() throws ExecutionException, InterruptedException {

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f1 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(5);

System.out.println("f1 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "fromF1";

}, executor);

CompletableFuture f2 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f2 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(2);

System.out.println("f2 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "fromF2";

}, executor);

CompletableFuture reslutFuture = f1.applyToEither(f2,i -> i.toString());

System.out.println(reslutFuture.get()); //should not be null , wait for complete

}

acceptEither(取2个future中最先返回的,无返回值)

/**

* 取其中返回最快的一个

* 当任意一个CompletionStage 完成的时候,action 这个消费者就会被执行。这个方法返回 CompletableFuture

*/

@Test

public void testAcceptEither() throws ExecutionException, InterruptedException {

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f1 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(3);

System.out.println("f1 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "zero";

}, executor);

CompletableFuture f2 = CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f2 start to sleep at:"+System.currentTimeMillis());

TimeUnit.SECONDS.sleep(5);

System.out.println("f2 stop sleep at:"+System.currentTimeMillis());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return "hello";

}, executor);

CompletableFuture reslutFuture = f1.acceptEither(f2,r -> {

System.out.println("quicker result:"+r);

});

reslutFuture.get(); //should be null , wait for complete

}

allOf与anyOf

allOf(等待所有future返回)

/**

* 等待多个future返回

*/

@Test

public void testAllOf() throws InterruptedException {

List> futures = IntStream.range(1,10)

.mapToObj(i ->

longCost(i)).collect(Collectors.toList());

final CompletableFuture allCompleted = CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{}));

allCompleted.thenRun(() -> {

futures.stream().forEach(future -> {

try {

System.out.println("get future at:"+System.currentTimeMillis()+", result:"+future.get());

} catch (InterruptedException | ExecutionException e) {

e.printStackTrace();

}

});

});

Thread.sleep(100000); //wait

}

anyOf(取多个future当中最快的一个返回)

/**

* 等待多个future当中最快的一个返回

* @throws InterruptedException

*/

@Test

public void testAnyOf() throws InterruptedException {

List> futures = IntStream.range(1,10)

.mapToObj(i ->

longCost(i)).collect(Collectors.toList());

final CompletableFuture firstCompleted = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[]{}));

firstCompleted.thenAccept((Object result) -> {

System.out.println("get at:"+System.currentTimeMillis()+",first result:"+result);

});

}

private CompletableFuture longCost(long i){

return CompletableFuture.supplyAsync(() -> {

try {

System.out.println("f"+i+" start to sleep at:"+System.currentTimeMillis());

Thread.sleep(3000);

System.out.println("f"+i+" stop sleep at:"+System.currentTimeMillis());

} catch (InterruptedException e) {

e.printStackTrace();

}

return String.valueOf(i);

},executor);

}

doc

java8 block_java8的CompletableFuture使用实例相关推荐

  1. java8 集合结合steam操作实例

    java8 集合结合steam操作实例 集合框架介绍:https://www.runoob.com/java/java-collections.html java8-streams:https://w ...

  2. Java8新特性--CompletableFuture

    并发与并行 Java 5并发库主要关注于异步任务的处理,它采用了这样一种模式,producer线程创建任务并且利用阻塞队列将其传递给任务的consumer.这种模型在Java 7和8中进一步发展,并且 ...

  3. java8中的lambda用法实例

    -----------------------------------------------------------下面是例子[1]--------------------------------- ...

  4. java8 supplyasync_java – 为什么CompletableFuture.supplyAsync成功随...

    我是Java 8中lambda和异步代码的新手.我不断得到一些奇怪的结果-- 我有以下代码: import java.util.concurrent.CompletableFuture; public ...

  5. Java8时间转换(LocalDateTime)代码实例

    1.将LocalDateTime转为自定义的时间格式的字符串 1 2 3 4 public static String getDateTimeAsString(LocalDateTime localD ...

  6. 《Java8实战》读书笔记10:组合式异步编程 CompletableFuture

    <Java8实战>读书笔记10:组合式异步编程 CompletableFuture 第11章 CompletableFuture:组合式异步编程 11.1 Future 接口 (只是个引子 ...

  7. Java8 - 使用CompletableFuture 构建异步应用

    文章目录 概述 同步API VS 异步API 同步的困扰 实现异步API 将同步方法改为异步方法 处理异常错误 概述 为了展示 CompletableFuture 的强大特性, 创建一个名为 best ...

  8. CompletableFuture详解~创建实例

    创建 CompletableFuture 对象实例我们可以使用如下几个方法: static CompletableFuture<U> completedFuture(U value)//使 ...

  9. Java8 提供CompletableFuture来简化高并发异步处理编程

    (摘录自狂乱的贵公子)所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法.在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需 ...

最新文章

  1. 微生物组-扩增子16S分析第12期(报名直播课免费参加线下2021.7)
  2. R语言split函数、unsplit函数按组拆分数据、合并数据实战
  3. numpy 打乱 numpy 数组
  4. BZOJ1787: [Ahoi2008]Meet 紧急集合
  5. Linux下内存泄露工具
  6. 用C++实现二分查找
  7. 数据结构排序系列详解之六 树形选择排序
  8. Android沉浸式(侵入式)标题栏(状态栏)Status(三)
  9. 51nod1130---斯特林公式
  10. 湖北 政府项目 软件 测试,湖北电子政务应用系统技术验收测试规范.doc
  11. 使用idea 把项目上传到 svn
  12. 探讨Python在开发中的重要性!
  13. 代码管理工具知多少?来看看Git怎么用吧
  14. 定期产品如何用活期的方式展示——逼近算法
  15. C#GridView获取选中当前行
  16. 防静电手环在计算机中的功能,无线静电手环是怎样防静电的原理是什么
  17. 拍摄婚纱的一天(2005-02-20)
  18. 算法竞赛入门经典第一节问题1-5
  19. 7.3Assertions and Defensive Programming断言与防御式编程
  20. Duplicate class/entity mapping 问题解决方法

热门文章

  1. elasticsearch工具类_Django + Elasticsearch——搜索精彩的TED演讲
  2. 讲讲 MySQL 中的 WAL 策略和 CheckPoint 技术
  3. web 自动化测试 selenium基础到应用(目录)
  4. Nginx报错:upstream timed out (110: Connection timed out)和client intended to send too large body【转】...
  5. 用路由做企业管理:所有人都说不可能的时候(中)
  6. 寻宝处理器的引人入胜之旅——《大话处理器》新书出炉
  7. 杭州市政府数据容灾集中备份业务整体外包(2009)项目招标公告
  8. 网络管理不简单 需化被动为主动
  9. mac下的secureCRT.8的设置
  10. cross-env使用 1