此特性还在孵化,后续版本可能有变动
//全部执行直到有失败的任务
String handle() throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> user = scope.fork(() -> "");
Future<Integer> order = scope.fork(() -> 1);
scope.join(); // Join both forks
scope.throwIfFailed(); // ... and propagate errors
// Here, both forks have succeeded, so compose their results
return user.resultNow()+order;
}
}
//有一个任务成功就会关闭资源返回结果
<T> T race(List<Callable<T>> tasks, Instant deadline) throws ExecutionException, InterruptedException, TimeoutException {
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<T>()) {
for (var task : tasks) {
scope.fork(task);
}
scope.joinUntil(deadline);
return scope.result(); // Throws if none of the forks completed successfully
}
}
标签:fork,jdk20,tasks,示例,Structured,var,scope,forks
From: https://www.cnblogs.com/funkboy/p/17356830.html