Java Thread.run() 返回值為 void,無法直接返回計算結果。需通過共享內存或 Future 模式獲取異步計算結果。
適用於簡單單次任務,手動控制等待。
public void test() throws InterruptedException {
final int[] result = new int[1];
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(() -> {
// 耗時計算
result[0] = computeHeavy();
latch.countDown(); // 釋放等待
});
t.start();
latch.await(); // 阻塞直到 countDown
System.out.println("Result: " + result[0]);
}
線程池管理,支持超時、取消、異常傳播,生產環境首選。
public void test() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable task = () -> computeHeavy();
Future future = executor.submit(task);
// 可做其他事...
Integer result = future.get(5, TimeUnit.SECONDS); // 支持超時
System.out.println("Result: " + result);
executor.shutdown();
}
鏈式組合、異步回調、多任務編排,現代 Java 首選。
public void test() {
CompletableFuture.supplyAsync(() -> computeHeavy())
.thenAccept(result -> System.out.println("Result: " + result))
.exceptionally(ex -> {
ex.printStackTrace();
return null;
});
// 主線程繼續執行,異步回調處理結果
}
| 維度 | CountDownLatch | Future | CompletableFuture |
|---|---|---|---|
| 複雜度 | 低 | 中 | 高 |
| 線程管理 | 手動 | 線程池 | ForkJoinPool/自定義 |
| 組合能力 | 無 | 有限 | 強大 |
| 異常處理 | 手動 | get()拋出 | exceptionally |
| 適用場景 | 簡單同步等待 | 標準異步任務 | 複雜異步流程 |
final 或 volatile 保證可見性,基本類型用數組包裝。future.get() 會阻塞調用線程,UI 線程慎用,應在後台線程或配合 thenAccept 使用。shutdown() 避免資源洩漏,長期運行應用建議單例線程池。根據業務複雜度選擇同步工具,拒絕在 run() 里寫死邏輯,擁抱現代並發 API。