CompletableFuture 异步获取结果

JDK1.8 提供的,用于弥补Future的重要不足点(get会阻塞)的一个类。大量用到了函数式编程的思想。image.png

1. 对结果进行转换

supplyAsync() 对结果进行转换

image.png

返回一个新的CompletableFuture,异步去执行一个任务。

thenApplyAsync()

image.png
在上一个CompletableFuture 执行完毕之后再去执行一个新的CompletableFuture。

2. 直接把结果处理掉

thenAccept() 消费

  1. String result = CompletableFuture.supplyAsync(() -> "hello").thenApplyAsync(value -> value + " world").join();
  2. System.out.println(result);
  3. System.out.println("========");
  4. CompletableFuture.supplyAsync(() -> "hello").thenAccept(value -> System.out.println("welcome " + value));
  5. System.out.println("========");


3. 对多个异步任务的结果合并

thenCombine()

  1. // 对于stage的合并操作
  2. String result2 = CompletableFuture.supplyAsync(() -> {
  3. try {
  4. Thread.sleep(1000);
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. return "hello";
  9. }).thenCombine(CompletableFuture.supplyAsync(() -> {
  10. try {
  11. Thread.sleep(2000);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. return "world";
  16. }), (s1, s2) -> s1 + " " + s2).join();
  17. System.out.println(result2);

whenComplete() 异步回调

  1. CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
  2. try {
  3. TimeUnit.MILLISECONDS.sleep(2000);
  4. } catch (InterruptedException e) {
  5. e.printStackTrace();
  6. }
  7. System.out.println("task finished");
  8. });
  9. completableFuture.whenComplete((t, action) -> System.out.println("执行完成!"));
  10. System.out.println("主线程执行完毕");
  11. try {
  12. TimeUnit.MILLISECONDS.sleep(7000);
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }

CompletionStage