java 线程池使用结构化并发管理任务,核心是引入 structuredtaskscope。它允许在父线程中派生子任务,并在指定策略(如 subtaskpolicy.all 或 subtaskpolicy.shutdown_on_failure)下等待子任务完成并处理结果。通过这种方式,可以简化并行任务的编排、错误处理和资源清理逻辑。

如何并行执行多个独立任务并获取所有结果?
要并行执行多个独立任务并获取所有结果,应使用 SubtaskPolicy.ALL。在这种模式下,所有子任务都会启动,即使某个任务抛出异常,其他任务也会继续运行。最终,join() 方法会返回一个包含所有成功结果的列表,如果任何任务失败,则抛出 ExecutionException。这种方法适用于需要收集所有结果且容忍部分失败的场景。

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.ExecutionException;
public class ParallelExample {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var task1 = scope.fork(() -> { Thread.sleep(100); return "Result 1"; });
var task2 = scope.fork(() -> { Thread.sleep(100); return "Result 2"; });
scope.join().throwIfFailed();
System.out.println("Results: " + task1.get() + ", " + task2.get());
}
}
}
如何在任一任务失败时立即取消其他任务?
若需在任一任务失败时立即取消其他任务,应使用 SubtaskPolicy.SHUTDOWN_ON_FAILURE。当任何一个子任务抛出异常时,作用域会自动中断所有其他正在运行的子任务,并终止整个作用域。这确保了资源的快速释放和故障的快速响应,适用于对延迟敏感或不允许部分成功的场景。

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.ExecutionException;
public class FailFastExample {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var task1 = scope.fork(() -> { Thread.sleep(50); throw new RuntimeException("Fail"); });
var task2 = scope.fork(() -> { Thread.sleep(200); return "Result 2"; });
try {
scope.join().throwIfFailed();
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause().getMessage());
}
}
}
}
StructuredTaskScope 的 close() 方法在什么情况下调用?
StructuredTaskScope 的 close() 方法通常在 try-with-resources 语句块结束时自动调用。如果在作用域内未发生异常,close() 会确保所有子任务已完成或已取消,并清理相关资源。如果发生异常,close() 仍会被调用以进行必要的清理,但此时可能已经触发了任务的取消逻辑。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











