【JUC】8-CompletableFutrue的常用方法

不会java的菜鸟程序员發表於2024-06-15

1、獲得結果和觸發計算

獲得結果

1 public T get()
2 
3 public T get(long timeOut, Timeunit unit)
4 
5 public T join()
6 
7 public getNow(T valueIfAbsent)

主動觸發計算

public boolean complete(T value)

2、對計算結果進行處理

計算結果存在依賴關係,這兩個執行緒序列化

1 thenApply()
計算結果存在依賴關係,這兩個執行緒序列化,步驟有異常也可以往下走,根據帶的異常引數可以進一步往下走
1 handle()

示例程式碼

  1 package com.heima.Thread;
  2 
  3 import java.util.concurrent.*;
  4 
  5 public class CompletableFutureApiDemo {
  6     private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(3);
  7 
  8     public static void main(String[] args) {
  9         try {
 10             // public T getNow(T valueIfAbsent)
 11             test_getNow();
 12             // public boolean complete(T value)  是否打斷get()方法立即返回括號值
 13             test_complete();
 14             // thenApply() 計算結果存在依賴關係,這兩個執行緒序列化
 15             test_thenApply();
 16             // handle() 計算結果存在依賴關係,這兩個執行緒序列化,步驟有異常也可以往下走,根據帶的異常引數可以進一步往下走
 17             test_handle();
 18         } finally {
 19             THREAD_POOL.shutdown();
 20         }
 21     }
 22 
 23     private static void test_handle() {
 24         CompletableFuture.supplyAsync(() -> {
 25             try {
 26                 TimeUnit.SECONDS.sleep(1);
 27             } catch (Exception e) {
 28                 e.printStackTrace();
 29             }
 30             System.out.println("step 1");
 31             return ThreadLocalRandom.current().nextInt();
 32         }, THREAD_POOL).handle((f, e) -> {
 33             int i = 10/0;
 34             System.out.println("step 2, get result " + f);
 35             return f + 2;
 36         }).handle((f, e) -> {
 37             System.out.println("step 3, get result " + f);
 38             return f * 3;
 39         }).whenComplete((v, e) -> {
 40             if (e == null) {
 41                 System.out.println("result is " + v);
 42             }
 43         }).exceptionally(e -> {
 44             e.printStackTrace();
 45             System.out.println(e.getMessage());
 46             return null;
 47         });
 48 
 49 
 50         // CompletableFuture使用預設的ForkJoinPool時,主執行緒結束時,其他執行緒也會結束
 51         System.out.println("Thread " + Thread.currentThread().getName() + " process other task.");
 52     }
 53 
 54     private static void test_thenApply() {
 55         CompletableFuture.supplyAsync(() -> {
 56             try {
 57                 TimeUnit.SECONDS.sleep(1);
 58             } catch (Exception e) {
 59                 e.printStackTrace();
 60             }
 61             System.out.println("step 1");
 62             return ThreadLocalRandom.current().nextInt();
 63         }, THREAD_POOL).thenApply(f -> {
 64             System.out.println("step 2, get result " + f);
 65             return f + 2;
 66         }).thenApply(f -> {
 67             System.out.println("step 3, get result " + f);
 68             return f * 3;
 69         }).whenComplete((v, e) -> {
 70             if (e == null) {
 71                 System.out.println("result is " + v);
 72             }
 73         }).exceptionally(e -> {
 74             e.printStackTrace();
 75             System.out.println(e.getMessage());
 76             return null;
 77         });
 78 
 79 
 80         // CompletableFuture使用預設的ForkJoinPool時,主執行緒結束時,其他執行緒也會結束
 81         System.out.println("Thread " + Thread.currentThread().getName() + " process other task.");
 82     }
 83 
 84 
 85     private static void test_getNow() {
 86 
 87         CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
 88             try {
 89                 TimeUnit.SECONDS.sleep(2);
 90             } catch (Exception e) {
 91                 e.printStackTrace();
 92             }
 93             return "ok";
 94         }, THREAD_POOL);
 95 
 96         System.out.println(result.getNow("not ok"));
 97 
 98     }
 99 
100     private static void test_complete() {
101         CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
102             try {
103                 TimeUnit.SECONDS.sleep(2);
104             } catch (Exception e) {
105                 e.printStackTrace();
106             }
107             return "ok";
108         }, THREAD_POOL);
109 
110         try {
111             TimeUnit.SECONDS.sleep(1);
112         } catch (Exception e) {
113             e.printStackTrace();
114         }
115         System.out.println(result.complete("completable ok") + "\t" + result. Join());
116     }
117 }

3、對計算結果進行消費

4、對計算速度進行選用

5、對計算結果進行合併

相關文章