Java多线程: 如何捕获多线程中的异常

简介: Java多线程: 如何捕获多线程中的异常

你处理过多线程中的异常吗?如何捕获多线程中发生的异常?捕获子线程的异常与捕获当前线程的异常一样简单吗?


除了try catch。Java中还可以通过异常处理器UncaughtExceptionHandler来处理那些未捕获的异常。


#  在当前线程捕获当前线程发生的异常:

/**
 * @author futao
 * @date 2020/6/17
 */
@Slf4j
public class ExceptionInCurThread {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("在主线程抛出异常,在主线程捕获");
        } catch (RuntimeException e) {
            log.error("捕获到异常", e);
        }
    }
}


  • 结果:


image.png

  • 结论:
    在当前线程通过try catch可以捕获当前线程抛出的异常。

# 可以在当前通过try catch的方式捕获其他线程抛出的异常吗?'

/**
 * @author 喜欢天文的pony站长
 * Created on 2020/6/16.
 */
public class ExceptionInChildThread implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException("子线程发生了异常...");
    }
    /**
     * 模拟子线程发生异常
     *
     * @throws InterruptedException
     */
    private static void exceptionThread() throws InterruptedException {
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
    }
    /**
     * 在主线程尝试通过try catch捕获异常
     */
    private static void catchInMain() {
        try {
            exceptionThread();
        } catch (Exception e) {
            //无法捕获发生在其他线程中的异常
            log.error("捕获到了异常?", e);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ExceptionInChildThread.catchInMain();
    }
}


  • (错误的)预期:
  • 在运行第一个线程的时候发生了异常,被catch捕获,打印捕获到了异常?和异常堆栈且后面的线程将不会运行。
  • 实际运行结果:
  • 并不符合预期。
  • 没有被try catch捕获。
  • 后续的线程没有因为第一个线程发生异常而跳过。



image.png

  • 结论:
  • 无法在一个线程中通过try catch捕获另外一个线程的异常。


# 解决方案



  1. 在每个线程内部run()方法内通过try catch捕获当前线程发生的异常。
  • 缺点:每个线程都需要编写重复的try catch 代码
  1. 使用线程异常处理器UncaughtExceptionHandler
  • 给所有线程设置统一的异常处理器
  • 给每个线程设置特定的异常处理器
  • 给线程组设置异常处理器
  • 给线程池设置异常处理器
  • 因为线程池也是通过new Thread()的方式创建的线程,所以思想与上面两种方法一致。
  • 注意:execute()与submit()方式对异常处理的不同。


# 在线程内部run()通过try catch捕获异常

/**
 * @author 喜欢天文的pony站长
 * Created on 2020/6/16.
 */
@Slf4j
public class ExceptionInChildThread implements Runnable {
    @Override
    public void run() {
        try {
            //do something else...
            throw new RuntimeException("子线程发生了异常...");
        } catch (Exception e) {
            log.error("在线程内部捕获异常", e);
        }
    }
    /**
     * 模拟子线程发生异常
     *
     * @throws InterruptedException
     */
    private static void exceptionThread() throws InterruptedException {
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
    }
    /**
     * 在主线程尝试通过try catch捕获异常
     */
    private static void catchInMain() {
        try {
            exceptionThread();
        } catch (Exception e) {
            //无法捕获发生在其他线程中的异常
            log.error("捕获到了异常?", e);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ExceptionInChildThread.catchInMain();
    }
}


  • 结果:
  • 成功在子线程内部run()方法捕获到了异常


image.png

# 使用线程异常处理器UncaughtExceptionHandler


当一个线程由于未捕获异常而退出时,JVM会把这个事件报告给应用程序提供的UncaughtExceptionHandler异常处理器


  • 自定义线程异常处理器

/**
 * 自定义线程未捕获异常处理器
 *
 * @author futao
 * @date 2020/6/17
 */
public class CustomThreadUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomThreadUncaughtExceptionHandler.class);
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        LOGGER.error("捕获到线程发生的异常,线程信息:[{}]", JSON.toJSONString(t), e);
    }
}
  • 使用:


1. 全局:


  • Thread.setDefaultUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());为我们自定的异常处理器。
  • 通过调用Thread的静态方法setDefaultUncaughtExceptionHandler(),设置Thread的静态属性defaultUncaughtExceptionHandler.
  • 源码:

image.png

image.png

  • 测试:

/**
 * @author 喜欢天文的pony站长
 * Created on 2020/6/16.
 */
@Slf4j
public class ExceptionInChildThread implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException("子线程发生了异常...");
    }
    /**
     * 模拟子线程发生异常
     *
     * @throws InterruptedException
     */
    private static void exceptionThread() throws InterruptedException {
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
    }
    public static void main(String[] args) throws InterruptedException {
        //设置全局的线程异常处理器
        Thread.setDefaultUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
        exceptionThread();
    }
}


  • 结果: 成功捕获


image.png

2. 为指定线程设置特定的异常处理器


  • 细心的同学已经发现了,在上面Thread类的截图中,还有一个实例属性private volatile UncaughtExceptionHandler uncaughtExceptionHandler;。通过给这个属性赋值,可以实现为每个线程对象设置不同的异常处理器。
  • 测试使用

/**
 * @author 喜欢天文的pony站长
 * Created on 2020/6/16.
 */
@Slf4j
public class ExceptionInChildThread implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException("子线程发生了异常...");
    }
    /**
     * 模拟子线程发生异常
     *
     * @throws InterruptedException
     */
    private static void exceptionThread() throws InterruptedException {
        Thread thread1 = new Thread(new ExceptionInChildThread());
        //为指定线程设置特定的异常处理器
        thread1.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
        thread1.start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
    }
    public static void main(String[] args) throws InterruptedException {
        exceptionThread();
    }
}


  • 结果: 成功捕获线程1的异常信息

image.png

3. 线程组

/**
 * @author futao
 * @date 2020/6/20
 */
@Slf4j
public class ExceptionInThreadGroup implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException("线程任务发生了异常");
    }
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup threadGroup = new ThreadGroup("只知道抛出异常的线程组...") {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                super.uncaughtException(t, e);
                log.error("线程组内捕获到线程[{},{}]异常", t.getId(), t.getName(), e);
            }
        };
        ExceptionInThreadGroup exceptionInThreadGroup = new ExceptionInThreadGroup();
        new Thread(threadGroup, exceptionInThreadGroup, "线程1").start();
        TimeUnit.MILLISECONDS.sleep(300L);
        //优先获取绑定在thread对象上的异常处理器
        Thread thread = new Thread(threadGroup, exceptionInThreadGroup, "线程2");
        thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
        thread.start();
        TimeUnit.MILLISECONDS.sleep(300L);
        new Thread(threadGroup, exceptionInThreadGroup, "线程3").start();
    }
}


  • 结果:


image.png


4. 线程池

/**
 * @author futao
 * @date 2020/6/17
 */
public class CatchThreadPoolException {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                4,
                1L,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(1024),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        //设置线程异常处理器
                        thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
                        return thread;
                    }
                }
        );
        threadPoolExecutor.execute(new Runnable() {
                                       @Override
                                       public void run() {
                                           throw new RuntimeException("execute()发生异常");
                                       }
                                   }
        );
        threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException("submit.run()发生异常");
            }
        });
        threadPoolExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                throw new RuntimeException("submit.call()发生异常");
            }
        });
      threadPoolExecutor.shutdown();
    }
}


  • 结果: 并不符合预期,预期应该捕获三个异常
  • 只捕获到了通过execute()提交的任务的异常
  • 没有捕获到通过submit()提交的任务的异常


image.png

  • 通过afterExecute()捕获submit()任务的异常
  • 通过submit()方法的源码可以发现,submit()是将runnable()封装成了RunnableFuture<Void>,并最终调用execute(ftask);执行。

/**
 * @author futao
 * @date 2020/6/17
 */
@Slf4j
public class CatchThreadPoolException {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                4,
                1L,
                TimeUnit.MINUTES,
                new LinkedBlockingDeque<>(1024),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        //设置线程异常处理器
                        thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
                        return thread;
                    }
                }
        ) {
            /**
             * 捕获{@code FutureTask<?>}抛出的异常
             *
             * @param r
             * @param t
             */
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                if (r instanceof FutureTask<?>) {
                    try {
                        //get()的时候会将异常内的异常抛出
                        ((FutureTask<?>) r).get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    } catch (ExecutionException e) {
                        log.error("捕获到线程的异常返回值", e);
                    }
                }
                //Throwable t永远为null,拿不到异常信息
                //log.error("afterExecute中捕获到异常,", t);
            }
        };
        threadPoolExecutor.execute(new Runnable() {
           @Override
           public void run() {
               throw new RuntimeException("execute()发生异常");
           }
       }
        );
        TimeUnit.MILLISECONDS.sleep(200L);
        threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException("submit.run()发生异常");
            }
        });
        TimeUnit.MILLISECONDS.sleep(200L);
        threadPoolExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                throw new RuntimeException("submit.call()发生异常");
            }
        }).get();   //get()的时候会将异常抛出
        threadPoolExecutor.shutdown();
    }
}


欢迎在评论区留下你看文章时的思考,及时说出,有助于加深记忆和理解,还能和像你一样也喜欢这个话题的读者相遇~


# 本文源代码



# 系列文章


相关文章
|
安全 算法 Java
Java 多线程:线程安全与同步控制的深度解析
本文介绍了 Java 多线程开发的关键技术,涵盖线程的创建与启动、线程安全问题及其解决方案,包括 synchronized 关键字、原子类和线程间通信机制。通过示例代码讲解了多线程编程中的常见问题与优化方法,帮助开发者提升程序性能与稳定性。
585 0
|
Java 程序员 数据库连接
我们详细地讲解一下 Java 异常及要如何处理
我是小假 期待与你的下一次相遇 ~
376 1
|
Java 数据挖掘 调度
Java 多线程创建零基础入门新手指南:从零开始全面学习多线程创建方法
本文从零基础角度出发,深入浅出地讲解Java多线程的创建方式。内容涵盖继承`Thread`类、实现`Runnable`接口、使用`Callable`和`Future`接口以及线程池的创建与管理等核心知识点。通过代码示例与应用场景分析,帮助读者理解每种方式的特点及适用场景,理论结合实践,轻松掌握Java多线程编程 essentials。
931 5
|
监控 搜索推荐 Java
Java 多线程最新实操技术与应用场景全解析:从基础到进阶
本文深入探讨了Java多线程的现代并发编程技术,涵盖Java 8+新特性,如CompletableFuture异步处理、Stream并行流操作,以及Reactive编程中的Reactor框架。通过具体代码示例,讲解了异步任务组合、并行流优化及响应式编程的核心概念(Flux与Mono)。同时对比了同步、CompletableFuture和Reactor三种实现方式的性能,并总结了最佳实践,帮助开发者构建高效、扩展性强的应用。资源地址:[点击下载](https://pan.quark.cn/s/14fcf913bae6)。
736 3
|
算法 Java 调度
Java多线程基础
本文主要讲解多线程相关知识,分为两部分。第一部分涵盖多线程概念(并发与并行、进程与线程)、Java程序运行原理(JVM启动多线程特性)、实现多线程的两种方式(继承Thread类与实现Runnable接口)及其区别。第二部分涉及线程同步(同步锁的应用场景与代码示例)及线程间通信(wait()与notify()方法的使用)。通过多个Demo代码实例,深入浅出地解析多线程的核心知识点,帮助读者掌握其实现与应用技巧。
272 1
java 多线程异常处理
本文介绍了Java中ThreadGroup的异常处理机制,重点讲解UncaughtExceptionHandler的使用。通过示例代码展示了当线程的run()方法抛出未捕获异常时,JVM如何依次查找并调用线程的异常处理器、线程组的uncaughtException方法或默认异常处理器。文章还提供了具体代码和输出结果,帮助理解不同处理器的优先级与执行逻辑。
310 1
|
机器学习/深度学习 监控 算法
局域网行为监控软件 C# 多线程数据包捕获算法:基于 KMP 模式匹配的内容分析优化方案探索
本文探讨了一种结合KMP算法的多线程数据包捕获与分析方案,用于局域网行为监控。通过C#实现,该系统可高效检测敏感内容、管理URL访问、分析协议及审计日志。实验表明,相较于传统算法,KMP在处理大规模网络流量时效率显著提升。未来可在算法优化、多模式匹配及机器学习等领域进一步研究。
401 0
|
数据采集 存储 网络协议
Java HttpClient 多线程爬虫优化方案
Java HttpClient 多线程爬虫优化方案
|
Java 数据库
【Java多线程】对线程池的理解并模拟实现线程池
【Java多线程】对线程池的理解并模拟实现线程池
482 155
|
存储 监控 Java
Java多线程优化:提高线程池性能的技巧与实践
Java多线程优化:提高线程池性能的技巧与实践
788 1