import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureWhenCompleteExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> {
// 模拟异步任务
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "异步任务执行结果";
}).whenComplete((result, exception) -> {
if (exception == null) {
System.out.println("任务执行成功,结果是: " + result);
} else {
System.out.println("任务执行出现异常: " + exception.getMessage());
}
});
// 主线程等待一会儿,确保异步任务有足够时间完成
Thread.sleep(3000);
}
}
whenComplete
方法参数含义:
result
:代表异步任务成功执行后的返回值,如果任务执行异常则为null
。
exception
:代表异步任务执行过程中抛出的异常,如果任务成功执行则为null
。通过这两个参数可以在异步任务完成时处理任务结果或异常情况。