使用线程池,当条线程的代码块出现问题,如果在线程池外获取这条线程
时间: 2023-10-26 22:05:43 浏览: 85
的异常信息,可以通过以下方式:
1. 在线程池中设置UncaughtExceptionHandler,当线程抛出未捕获的异常时,会调用该handler处理异常。
```
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, new ThreadFactoryBuilder().setNameFormat("pool-%d").build());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("pool-%d").setUncaughtExceptionHandler((t, e) -> {
System.out.println("线程 " + t.getName() + " 抛出异常:" + e.getMessage());
}).build());
```
2. 使用Future.get()方法获取线程执行结果时,如果线程抛出异常,则get()方法会抛出ExecutionException异常,其中包含了原始异常信息。
```
Future<String> future = executor.submit(() -> {
throw new RuntimeException("异常信息");
});
try {
String result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
System.out.println("线程抛出异常:" + e.getCause().getMessage());
}
```
阅读全文