Java 线程池中 submit 返回 Future 怎么使用
在 java 线程池中使用 submit() 提交任务后,会立即得到一个 future> 对象。要获取结果或判断状态,需要调用该对象的 get()、isdone() 等方法。如果不调用 get() 且未捕获异常,线程池中的工作线程可能会静默吞掉异常。

如何正确获取异步计算的结果
通过调用 Future.get() 可以阻塞当前线程直到任务完成并返回结果。该方法会抛出 ExecutionException(包装了任务的异常)和 InterruptedException。为了安全地获取结果,通常需要在 try-catch 块中处理这些受检异常。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
// 提交一个返回整数的任务
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000); // 模拟耗时操作
return 42;
});
try {
// 阻塞等待结果
Integer result = future.get();
System.out.println("Result: " + result);
} catch (ExecutionException e) {
System.err.println("Task failed: " + e.getCause());
} finally {
executor.shutdown();
}
}
}
如何处理任务执行过程中的异常
当任务内部抛出未捕获的异常时,Future.get() 不会直接抛出原始异常,而是将其包裹在 ExecutionException 中。因此,必须检查 getCause() 来获取真正的错误原因。此外,如果不调用 get(),异常将仅在后台线程中被忽略,导致难以排查的问题。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.*;
public class FutureExceptionExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
// 提交一个会抛出异常的任务
Future<String> future = executor.submit(() -> {
throw new RuntimeException("Something went wrong");
});
try {
String result = future.get();
} catch (ExecutionException e) {
// 获取原始异常
Throwable cause = e.getCause();
System.err.println("Caught exception: " + cause.getMessage());
} finally {
executor.shutdown();
}
}
}

















