我正在测试如何CompletableFuture工作。我对如何并行执行任务感兴趣:
try {
CompletableFuture one = CompletableFuture.runAsync(() -> {
throw new RuntimeException("error");
});
CompletableFuture two = CompletableFuture.runAsync(() -> System.out.println("2"));
CompletableFuture three = CompletableFuture.runAsync(() -> System.out.println("3"));
CompletableFuture all = CompletableFuture.allOf(one, two, three);
all.get();
} catch (InterruptedException e) {
System.out.println(e);
} catch (ExecutionException e) {
System.out.println(e);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,他们将全部被处决。
1 . 当其中一个线程出现异常时,是否可以中断所有正在运行的线程?
2 . 当此代码位于可以从不同线程调用的类方法内部时,它是线程安全的吗?