多线程异常处理需特殊措施。1. run()中用try-catch捕获;2. 设置UncaughtExceptionHandler处理未捕获异常;3. 使用Callable+Future,通过get()获取ExecutionException;4. 自定义ThreadFactory为线程池统一设置处理器。生产环境推荐后两者。
Java多线程中,异常处理比单线程复杂,因为子线程中的异常不会自动传递到主线程。如果不做特殊处理,线程内部抛出的异常可能导致程序静默失败。下面介绍几种常见的多线程异常捕获与处理方法。
1. 使用 try-catch 捕获异常
最直接的方式是在线程的 run() 方法中使用 try-catch 包裹执行逻辑:
- 适用于自定义线程或实现 Runnable 接口的场景
- 可以记录日志、通知外部系统或进行恢复操作
示例代码:
new Thread(() -> { try { // 可能出错的业务逻辑 int result = 10 / 0; } catch (Exception e) { System.err.println("线程内捕获异常: " + e.getMessage()); } }).start();
2. 实现 UncaughtExceptionHandler
当线程运行时未被捕获的异常(即“未捕获异常”)发生时,jvm 会调用线程关联的 UncaughtExceptionHandler。
立即学习“Java免费学习笔记(深入)”;
- 可以通过 Thread.setUncaughtExceptionHandler() 设置单个线程的处理器
- 也可以通过 Thread.setDefaultUncaughtExceptionHandler() 设置全局默认处理器
示例:
Thread thread = new Thread(() -> { throw new RuntimeException("测试异常"); }); thread.setUncaughtExceptionHandler((t, e) -> { System.err.println("线程 " + t.getName() + " 发生异常: " + e.getMessage()); }); thread.start();
3. 使用 Callable 和 Future 获取异常
使用 ExecutorService 提交 Callable 任务时,异常会在调用 Future.get() 时以 ExecutionException 的形式抛出。
- Callable 的 call() 方法允许抛出异常
- Future.get() 能捕获执行过程中的异常,便于集中处理
示例:
ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(() -> { return 10 / 0; }); try { Integer result = future.get(); // 此处抛出 ExecutionException } catch (ExecutionException e) { System.err.println("任务执行异常: " + e.getCause().getMessage()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
executor.shutdown();
4. 自定义线程工厂统一设置异常处理器
在使用线程池时,可以通过自定义 ThreadFactory 为每个创建的线程设置统一的异常处理器。
示例:
ThreadFactory factory = r -> { Thread t = new Thread(r); t.setUncaughtExceptionHandler((thread, exception) -> { System.err.println("工厂创建的线程异常: " + thread.getName() + ", 错误: " + exception.getMessage()); }); return t; }; ExecutorService executor = Executors.newFixedThreadPool(2, factory);
基本上就这些常见方式。根据实际使用场景选择合适的方法:简单任务可用 try-catch,生产环境推荐结合 Callable/Future 或统一异常处理器,确保异常不被遗漏。
评论(已关闭)
评论已关闭