常用方法
- supplyAsync:异步运行任务并带有返回值
- runAsync:异步运行任务没有返回值
- get:获取返回值
- thenApplyAsync:任务执行完毕后异步执行下一个任务并带有返回值
- thenRunAsync:任务执行完毕后异步执行下一个任务没有返回值
- thenCompose:任务执行完毕后将结果作为参数执行下一个任务
- allOf:所有任务完成后返回一个新的任务
- anyOf:当任意任务完成后返回一个新的任务
- runAfterBothAsync:当两个任务运行结束后异步运行任务
代码实例
- 三个任务完成后,执行第四个任务计算前四个任务的合
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 1 is running on thread " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 1 completed.");
return 1;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 2 is running on thread " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 2 completed.");
return 2;
});
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 3 is running on thread " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 3 completed.");
return 3;
});
CompletableFuture<Void> allTasks = CompletableFuture.allOf(future1, future2, future3);
CompletableFuture<Integer> combinedFuture = allTasks.thenCompose(v ->
CompletableFuture.supplyAsync(() -> {
int result = 0;
try {
result = future1.get() + future2.get() + future3.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return result;
})
);
try {
System.out.println("Combined result of Task 1, Task 2, and Task 3: " + combinedFuture.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}