java
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
//模拟执行耗时任务
⼀ System.out.println("task1 doing...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//返回结果
return "result1";
});
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
//模拟执行耗时任务
System.out.println("task2 doing...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//返回结果
return "result2";
});
CompletableFuture<Object> anyResult = CompletableFuture.anyOf(task1, task2);
CompletableFuture<Void> allResult = CompletableFuture.allOf(task1, task2);
System.out.println("第一个完成的任务结果:" + anyResult.get());
System.out.println("任务结果:" + allResult.get());
//阻塞等待所有任务执行完成
anyResult.join();
String s = task1.get();
String s2 = task2.get();
System.out.println("所有任务执行完成");
System.out.println(s);
System.out.println(s2);
}
}