Java中常用的異步方法
1、使用線程:你可以創建一個新的線程來執行異步操作。這可以通過直接創建Thread對象并啟動它,或者使用線程池來管理線程的生命周期。
new Thread(() -> {// 異步操作代碼
}).start();
2、使用線程池Executor框架:Executor框架提供了一種更高級別的異步執行機制,可以管理線程池和任務調度。
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {// 異步操作代碼
});
executor.shutdown();
3、使用Java 8引入的CompletableFuture類:CompletableFuture類提供了一種更便捷的方式來執行異步操作,并處理操作完成后的結果。
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {// 異步操作代碼
});// 可以在異步操作完成后執行回調函數
future.thenRun(() -> {// 操作完成后的處理代碼
});
4、使用第三方庫:除了Java內置的工具,還有許多第三方庫可用于實現異步操作,例如Guava的ListenableFuture等。
CompletableFuture類使用
CompletableFuture 類是 Java 中用于處理異步編程的強大工具。下面是 CompletableFuture 類的一些常用方法的詳細解釋:?
1. ?supplyAsync(Supplier<U> supplier) :創建一個 CompletableFuture,該 CompletableFuture 會異步執行 Supplier 方法,并返回計算結果。 ?
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {// 異步操作:計算兩個整數的和int a = 5;int b = 10;return a + b;
});
// get() 方法,該方法是阻塞的,直到異步操作完成或超時。
Integer val = future.get();
System.out.println("獲取異步加載的值:" + val);
2. ?thenApply(Function<? super T,? extends U> fn) :在 CompletableFuture 完成后應用給定的函數 fn,將 CompletableFuture 的結果轉換為另一種類型,并返回一個新的 CompletableFuture。 ?
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {// 異步操作:獲取用戶年齡return getUserAge();
}).thenApply(age -> {// 將年齡轉換為字符串return "返回用戶年齡信息: " + String.valueOf(age);
});
3. ?thenAccept(Consumer<? super T> action) :在 CompletableFuture 完成后執行給定的動作 action,對 CompletableFuture 的結果進行消費,但不返回新的 CompletableFuture。 ?
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {// 異步操作:獲取用戶年齡return getUserAge();
}).thenAccept(age -> {// 沒有返回值System.out.println("thenAccept沒有返回值: " + String.valueOf(age));
});
4. ?thenRun(Runnable action) :在 CompletableFuture 完成后執行給定的動作 action,對 CompletableFuture 的結果不進行消費,也不返回新的 CompletableFuture。 ?
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {// 返回值return "Result";
});CompletableFuture<Void> thenRunFuture = future.thenRun(() -> {// 使用 thenRun() 執行一個操作,在計算完成后打印一條消息System.out.println("執行完成!");
});// 獲取值
thenRunFuture.get();
5. ?thenCompose(Function<? super T,? extends CompletionStage<U>> fn) :在 CompletableFuture 完成后應用給定的函數 fn,將 CompletableFuture 的結果傳遞給該函數,并返回一個新的 CompletableFuture。簡單的說就是用于將兩個 CompletableFuture 對象串聯起來執行。
// 使用場景:
// 假設有兩個異步任務,任務 A 返回一個結果,任務 B 根據任務 A 的結果進行計算并返回最終結果。
CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {// 異步任務 Areturn 2;
});CompletableFuture<Integer> futureB = futureA.thenCompose(resultA -> {// 異步任務 B,根據任務 A 的結果進行計算int resultB = resultA * 3;return CompletableFuture.completedFuture(resultB);
});// 最終結果輸出6
futureB.thenAccept(finalResult -> System.out.println("最終結果:" + finalResult));
6. ?exceptionally(Function<Throwable,? extends T> fn) :在 CompletableFuture 發生異常時應用給定的函數 fn,返回一個新的 CompletableFuture,該 CompletableFuture 的結果是由異常處理函數提供的,用于處理異步任務中的異常情況.
// 使用場景:
// 假設有一個異步任務,計算兩個數的商,出現除零異常。在發生異常時返回一個默認值
CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {int dividend = 10;int divisor = 0;return dividend / divisor;
});CompletableFuture<Double> resultFuture = future.exceptionally(ex -> {System.out.println("發生異常:" + ex);return 0.0; // 返回默認值
});// 輸出:
// 發生異常:java.lang.ArithmeticException: / by zero
// 計算結果:0.0
resultFuture.thenAccept(result -> System.out.println("計算結果:" + result));
7. ?handle(BiFunction<? super T,Throwable,? extends U> fn) :在 CompletableFuture 完成后應用給定的函數 fn,無論 CompletableFuture 是否發生異常,該函數都會被調用,并返回一個新的 CompletableFuture,用于處理異步任務的結果(包括正常結果和異常情況)。
CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {int dividend = 10;int divisor = 2;return dividend / divisor;
});CompletableFuture<String> resultFuture = future.handle((result, ex) -> {if (ex != null) {System.out.println("發生異常:" + ex);return "默認值"; // 返回默認值} else {return "計算結果:" + result;}
});// 輸出:
// 計算結果:5.0
resultFuture.thenAccept(result -> System.out.println(result));
8. ?allOf(CompletableFuture<?>... cfs) :等待多個 CompletableFuture 完成,并返回一個新的 CompletableFuture,該新的 CompletableFuture 在所有輸入的 CompletableFuture 都完成后才會完成。?
注意:allOf() 方法返回的是 CompletableFuture<Void> ,因為它只關注所有CompletableFuture的完成狀態,而不關心具體的結果。如果你需要獲取每個CompletableFuture的結果,你可以在 allOf() 之后使用 get() 方法來獲取每個CompletableFuture的結果。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;public class CompletableFutureExample {public static void main(String[] args) {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 1";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 2";});CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 3";});CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);try {allFutures.get();System.out.println("所有任務都完成了,開始獲取值:");System.out.println("獲取 Future 1 的值: " + future1.get());System.out.println("獲取 Future 2 的值: " + future2.get());System.out.println("獲取 Future 3 的值: " + future3.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}
}
9. ?anyOf(CompletableFuture<?>... cfs) :等待多個 CompletableFuture 中的任意一個完成,并返回一個新的 CompletableFuture,該新的 CompletableFuture 在其中任意一個 CompletableFuture 完成時就會完成。?
CompletableFuture.anyOf() 方法常用于以下場景:當你想并發執行多個異步任務,并且只需要獲取第一個完成的任務的結果時,它非常有用。在有多個獨立任務且只關心第一個成功完成的任務結果時,它可以發揮作用。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;public class CompletableFutureExample {public static void main(String[] args) {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 1";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 2";});CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}return "Result from Future 3";});CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2, future3);try {System.out.println("打印任務的完成狀態: " + anyFuture.isDone());Object result = anyFuture.get();System.out.println("有一個任務完成了,就不管別的任務了: " + result);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}
}
Future 和 AsyncResult的區別和使用場景
1. Future 接口:?
? ?- Future 接口是 Java 提供的一個異步操作的結果的占位符。它表示一個可能完成或者失敗的異步操作。?
? ?- Future 接口提供了一些方法(如 ?get() 、 isDone() 、 cancel() ?等)來獲取異步操作的結果、檢查操作是否完成以及取消操作。?
? ?- Future 接口的一個主要限制是它只能通過輪詢來判斷異步操作是否完成,這樣可能會導致線程阻塞。?
// get()獲取值
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, World!");
String result = future.get();
System.out.println("阻塞直到獲取值" + result);// isDone()是否完成
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, World!");
boolean done = future.isDone();
System.out.println("任務是否完成:" + done);// cancel()取消異步任務的執行
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {// 模擬一個長時間運行的任務try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}return "Hello, World!";
});
boolean canceled = future.cancel(true);
System.out.println("任務是否被取消:" + canceled);
2. AsyncResult 接口:?
? ?- AsyncResult 接口是 Vert.x 框架中的一個特定實現,用于表示異步操作的結果。?
? ?- AsyncResult 接口繼承自 Future 接口,并提供了更多的方法和功能,使得處理異步操作更加方便。?
? ?- AsyncResult 接口提供了一種更靈活的方式來處理異步操作的結果,包括處理成功和失敗的情況,并可以獲取操作的異常信息。?
// 此處使用了異步注解、結合AsyncResult使用的舉例
@Async(THREAD_NAME)
public Future<Integer> ruleTotal() {return new AsyncResult<Integer>(testMapper.obtainCount());
}