在Java中,当我们使用线程池执行任务时,一般有两种方法:execute() 和 submit()。
execute() 方法接收一个 Runnable 对象,没有返回值。如果在任务执行过程中出现异常,异常将被打印出来,但我们不能获取到该异常。
submit() 方法接收一个 Callable 或 Runnable 对象,返回一个 Future 对象。我们可以通过 Future 对象获取任务执行结果,包括执行过程中抛出的异常。
下面是一个示例,展示如何使用线程池并获取任务的执行结果(包括异常):
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(1);
//方式1
Future<?> future = executor.submit(()->{
//
int i=1/0;
return null;
});
// //方式2
// Future<?> future = executor.submit(new TaskWithException());
try {
future.get();
} catch (Exception e) {
// 任务中的异常会被封装在 ExecutionException 中
System.out.println("Exception from task: " + e.getCause().getMessage());
} finally {
executor.shutdown();
}
}
static class TaskWithException implements Callable<Void> {
@Override
public Void call() throws Exception {
int i=1/0;
return null;
}
}
}
在这个示例中,我们创建一个线程池并提交一个会抛出异常的任务。我们使用 submit() 方法提交任务,这样我们就可以通过返回的 Future 对象获取任务的执行结果,包括任何在任务执行过程中抛出的异常。在调用 future.get() 时,如果任务抛出了异常,那么这个异常会被封装在一个 ExecutionException 中并被抛出。
注意,在实际应用中,我们需要确保在使用完线程池后调用 shutdown() 方法来关闭线程池,防止资源泄露。