import java.util.concurrent.CompletableFuture;
public class AsyncTaskExample {
public static void main(String[] args) {
CompletableFuture<Void> taskA = CompletableFuture.runAsync(() -> {
System.out.println("Task A is running.");
// 模拟任务A执行耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
CompletableFuture<Void> taskB = taskA.thenRunAsync(() -> {
System.out.println("Task B is running.");
// 模拟任务B执行耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
CompletableFuture<Void> taskC = taskA.thenRunAsync(() -> {
System.out.println("Task C is running.");
// 模拟任务C执行耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(taskB, taskC);
combinedFuture.whenComplete((result, exception) -> {
if (exception != null) {
System.out.println("An exception occurred during Task B or Task C: " + exception.getMessage());
} else {
System.out.println("Both Task B and Task C completed successfully. Starting Task D.");
CompletableFuture.runAsync(() -> {
System.out.println("Task D is running.");
// 模拟任务D执行耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).whenComplete((res, ex) -> {
if (ex != null) {
System.out.println("An exception occurred during Task D: " + ex.getMessage());
} else {
System.out.println("Task D completed successfully.");
}
});
}
});
}
}
各环节whenComplete
方法的具体作用
combinedFuture.whenComplete
:
- 作用:用于监听任务B和任务C的完成情况。当任务B和任务C都完成时,会执行这个
whenComplete
中的代码块。
- 具体实现:在
whenComplete
的代码块中,首先检查是否有异常发生(通过exception != null
判断)。如果有异常,打印出异常信息;如果没有异常,说明任务B和任务C都成功完成,然后启动任务D。
- 任务D中的
whenComplete
:
- 作用:用于监听任务D的完成情况。当任务D完成时,会执行这个
whenComplete
中的代码块。
- 具体实现:同样检查是否有异常发生(通过
ex != null
判断)。如果有异常,打印出异常信息;如果没有异常,打印任务D成功完成的信息。