ExecutorService executorService= Executors.newFixedThreadPool(3);
Future<String> user = executorService.submit(() -> getUser());
Future<Integer> order = executorService.submit(() -> getOrder());
String theUser = user.get(); // 加入 getUser
int theOrder = order.get(); // 加入 getOrder
public class Test {
public static void main(String[] args) {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> userFuture = scope.fork(() -> getUser());
Future<Integer> orderFuture = scope.fork(() -> getOrder());
scope.join() // Join both subtasks
.throwIfFailed(); // ... and propagate errors
System.out.println("User: " + userFuture.get());
System.out.println("Order: " + orderFuture.get());
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
private static int getOrder() throws Exception {
// throw new Exception("test");
return 1;
}
private static String getUser() {
return "user";
}
}
Exception in thread "main" java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.Exception: test
at Test.main(Test.java:21)
Caused by: java.util.concurrent.ExecutionException: java.lang.Exception: test
at jdk.incubator.concurrent/jdk.incubator.concurrent.StructuredTaskScope$ShutdownOnFailure.throwIfFailed(StructuredTaskScope.java:1188)
at Test.main(Test.java:17)
Caused by: java.lang.Exception: test
at Test.getOrder(Test.java:26)
at Test.lambda$main$1(Test.java:15)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
at java.base/java.lang.VirtualThread.run(VirtualThread.java:305)
at java.base/java.lang.VirtualThread$VThreadContinuation.lambda$new$0(VirtualThread.java:177)
at java.base/jdk.internal.vm.Continuation.enter0(Continuation.java:327)
at java.base/jdk.internal.vm.Continuation.enter(Continuation.java:320)
阅读量:2018
点赞量:0
收藏量:0