解析Java线程池的异常处理机制

简介: 该内容是一个关于Java线程和线程池异常处理的总结。提到的关键点包括:1. 引用了滑动验证页面和相关文章资源。2. 区分了`execute`与`submit`在处理线程异常时的区别,`submit`可能会捕获并隐藏异常,而`execute`会直接抛出。3. 提供了处理线程和线程池异常的建议,如使用try/catch直接捕获,或者自定义线程工厂和未捕获异常处理器。4. 示例代码展示了如何通过设置`UncaughtExceptionHandler`来监控和处理线程中的异常。请注意,由于字符限制,这里只提供了简要摘要,详细解释和代码示例请参考原文。

 

感谢:1、滑动验证页面

2、线程的异常捕获与线程池的异常捕获 execute与submit区别:线程的异常捕获与线程池的异常捕获 execute与submit区别_threadutil.execute-CSDN博客

原文:https://www.cnblogs.com/wscit/p/6100476.html

3、线程吞掉异常信息 - 简书

submit的方式会吃掉异常,execute的方式会直接抛出

之后定义的时候要这样定义

对于线程池、包括线程的异常处理推荐一下方式:

  1. 直接try/catch
@Test
    public void catchThreadPoolTest() {
        ExecutorService threadPool = Executors.newFixedThreadPool(1);
        try {
            Runnable runnable = () -> {
                System.out.println("-----------submit---------------");
                Object obj = null;
                System.out.println(obj.toString());
            };
            threadPool.submit(runnable).get();
        } catch (Exception e) {
            System.out.println("---------submit  Exception---------");
            e.printStackTrace();
        }
        System.out.println("-----------华丽的分割线---------------");
        threadPool.execute(() -> {
            try {
                Object obj = null;
                System.out.println(obj.toString());
            } catch (Exception e) {
                System.out.println("---------execute  Exception-----------");
                e.printStackTrace();
            }
        });
    }

image.gif

2、线程直接重写整个方法:

第一段代码仅限于execute方法,因为submit的异常在线程池定义那块捕获不到,只有get的时候才会抛出,并且影响主线程的进行


@Test
    public void threadPoolTest() {
        ExecutorService threadPool = Executors.newFixedThreadPool(1, r -> {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler(
                    (t1, e) -> System.out.println(t1 + " throws exception: " + e));
            return t;
        });
        threadPool.execute(() -> {
            System.out.println("-----------execute---------------");
            Object obj = null;
            System.out.println(obj.toString());
            System.out.println("-----------obj.toString---------------");
        });
        System.out.println("-----------afterExecue---------------");
    }
image.gif


@Test
    public void catchedExecutor() {
        ExecutorService executorService = Executors.newCachedThreadPool(new MyThreadFactory());
        executorService.execute(new Task());
        executorService.shutdownNow();
        System.out.println("-----------start---------------");
    }
public class MyThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setUncaughtExceptionHandler(new RewriteUncatchtExceptionHandler());
        System.out.println("Thread[" + t.getName() + "] created.");
        return t;
    }
}
public class Task implements Runnable {
    public void run() {
        System.out.println("执行任务");
        int num  = Integer.parseInt("TT");
    }
}
public class RewriteUncatchtExceptionHandler implements Thread.UncaughtExceptionHandler {
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("我捕获到了线程池的异常");
    }
}
image.gif


@Test
    public void rewriteUncaughtException() {
        Task task = new Task();
        Thread thread = new Thread(task);
        thread.setUncaughtExceptionHandler(new RewriteUncatchtExceptionHandler());
        thread.start();
        System.out.println("-----------start---------------");
    }
public class RewriteUncatchtExceptionHandler implements Thread.UncaughtExceptionHandler{
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("我捕获到了线程池的异常");
    }
}
public class Task implements Runnable {
    public void run() {
        System.out.println("执行任务");
        int num  = Integer.parseInt("TT");
    }
}
image.gif


@Test
    public void rewriteAfterExecute() {
        ExecutorService threadPool2 = new MyThreadPoolExecutor(1, 1, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
        threadPool2.execute(() -> {
            System.out.println("-----------execute---------------");
            Object obj = null;
            System.out.println(obj.toString());
        });
        System.out.println("-----------afterExecue---------------");
    }
public class MyThreadPoolExecutor extends ThreadPoolExecutor {
    public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
    protected void afterExecute(Runnable r, Throwable t) {
        if(t!=null){
            System.out.println("MyThreadPoolExecutor     "+t);
        }
    }
}
image.gif

Thread t = new Thread();
       t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
 
public void uncaughtException(Thread t, Throwable e) {
LOGGER.error(t + " throws exception: " + e);
}
        });
        //如果是线程池的模式:
        ExecutorService threadPool = Executors.newFixedThreadPool(1, r -> {
 Thread t = new Thread(r);
 t.setUncaughtExceptionHandler(
  (t1, e) -> LOGGER.error(t1 + " throws exception: " + e));
 return t;
        });
  1. image.gif
目录
相关文章
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
存储 安全 Java
《数据之美》:Java集合框架全景解析
Java集合框架是数据管理的核心工具,涵盖List、Set、Map等体系,提供丰富接口与实现类,支持高效的数据操作与算法处理。
|
Java 开发者
Java 函数式编程全解析:静态方法引用、实例方法引用、特定类型方法引用与构造器引用实战教程
本文介绍Java 8函数式编程中的四种方法引用:静态、实例、特定类型及构造器引用,通过简洁示例演示其用法,帮助开发者提升代码可读性与简洁性。
|
Java 开发者
Java并发编程:CountDownLatch实战解析
Java并发编程:CountDownLatch实战解析
703 100
|
机器学习/深度学习 JSON Java
Java调用Python的5种实用方案:从简单到进阶的全场景解析
在机器学习与大数据融合背景下,Java与Python协同开发成为企业常见需求。本文通过真实案例解析5种主流调用方案,涵盖脚本调用到微服务架构,助力开发者根据业务场景选择最优方案,提升开发效率与系统性能。
2429 0
|
Java 程序员 编译器
十三、Java异常处理机制详解
异常机制是指程序在执行过程中发生了不正常的情况。
十三、Java异常处理机制详解
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
651 1
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
575 1
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案
Java 数据库 Spring
545 0

热门文章

最新文章

推荐镜像

更多
  • DNS