public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(5,6,7);
// 可以join等待结果
for (Integer i : list) {
System.out.println("你好...");
CompletableFuture.allOf(list2.stream().map(a -> CompletableFuture.runAsync(() ->{
// 这里是你想要异步执行的代码
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Running task " + a);
})).toArray(CompletableFuture[]::new)).join();
}
// 直接返回收集的结果
list2.stream()
.map(a -> CompletableFuture.runAsync(() -> {
try {
System.out.println(a);
} catch (Exception e) {
throw new RuntimeException(e);
}
}).exceptionally(throwable -> {
System.out.println("发生异常: " + throwable.getMessage());
return null;
})).collect(Collectors.toList())
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
}
并发编程实战CompletableFuture-01
于 2024-05-22 23:09:40 首次发布