completablefuture 的 isdone() 方法用于检查任务是否已经完成,包括正常结束、异常结束或被取消的情况。调用该方法不会阻塞当前线程,适合在轮询或状态判断场景中使用。如果任务尚未完成,isdone() 返回 false;如果已完成(无论成功还是失败),则返回 true。

isDone() 与 isCompletedExceptionally() 的区别是什么
isDone() 仅表示任务已结束,不区分是成功还是异常。若需判断是否因异常而结束,应使用 isCompletedExceptionally()。两者结合可覆盖所有终止状态。

import java.util.concurrent.CompletableFuture;
public class IsDoneDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Simulated error");
}
return "Success";
});
Thread.sleep(100);
System.out.println("Is done: " + future.isDone());
System.out.println("Is completed exceptionally: " + future.isCompletedExceptionally());
try {
String result = future.get();
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
运行结果示例(取决于随机数):
Is done: true
Is completed exceptionally: true/false
Result: Success 或 Exception caught: Simulated error
立即学习“Java免费学习笔记(深入)”;
如何在不阻塞的情况下等待 isDone() 变为 true
可以使用 wait() 配合 synchronized 块,或使用 CountDownLatch、FutureTask 等机制。但更推荐的方式是使用 whenComplete() 或 thenAccept() 等异步回调方法,避免手动轮询和阻塞。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
public class WaitUntilDoneDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Done";
});
CountDownLatch latch = new CountDownLatch(1);
future.whenComplete((result, ex) -> latch.countDown());
latch.await(); // 阻塞直到任务完成
System.out.println("Task is done: " + future.isDone());
System.out.println("Result: " + future.join());
}
}
该程序确保主线程在任务完成后才继续执行,并安全获取结果。


















