调用 completablefuture 实例的 get() 方法即可阻塞当前线程并获取异步计算的结果。该方法会一直挂起直到任务完成,期间若任务抛出异常则包装为 executionexception 返回,若被中断则抛出 interruptedexception。开发者只需在需要结果的地方直接调用此方法,无需关心底层线程状态。

get() 方法如何处理执行异常与中断
当异步任务内部发生运行时异常时,get() 不会直接抛出原始异常,而是将其包裹在 ExecutionException 中,需通过 Cause 获取真实错误;同时若等待过程中主线程被中断,将立即抛出 InterruptedException 并清除中断状态。这要求调用方必须处理这两类受检异常,否则程序可能因未捕获异常而终止。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Demo {
public static void main(String[] args) {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) throw new RuntimeException("Calc error");
return "Success";
});
try {
String result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
System.err.println(e.getCause());
}
}
}</string>
get() 与带超时参数的 get(long, TimeUnit) 区别
无参 get() 会无限期阻塞直到结果可用,适合确定任务必完成且允许长时间等待的场景;而带超时参数的版本会在指定时间内未收到结果时抛出 TimeoutException,防止线程永久挂起。两者均会阻塞当前线程,但后者提供了更细粒度的控制能力,避免资源浪费。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeoutDemo {
public static void main(String[] args) {
CompletableFuture<string> slowFuture = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(2000); } catch (InterruptedException e) {}
return "Done";
});
try {
String res = slowFuture.get(1, TimeUnit.SECONDS);
System.out.println(res);
} catch (TimeoutException e) {
System.out.println("Timed out");
} catch (Exception e) {
e.printStackTrace();
}
}
}</string>
使用 get() 时如何判断任务是否已完成
虽然 get() 本身不检查完成状态,但可通过 isDone() 方法预先判断任务是否已结束。若 isDone() 返回 true,则 get() 将立即返回结果而不阻塞;若为 false,则进入阻塞等待。这种组合方式可用于实现非阻塞重试或轮询逻辑,提升对异步任务状态的掌控力。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










