解析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
目录
相关文章
|
20天前
|
Java
Java中ReentrantLock释放锁代码解析
Java中ReentrantLock释放锁代码解析
25 8
|
1天前
|
安全 算法 关系型数据库
线程安全--深入探究线程等待机制和死锁问题
线程安全--深入探究线程等待机制和死锁问题
|
5天前
|
XML Java 开发工具
阿里云大学考试Java高级题目及解析-java高级
阿里云大学考试Java高级题目及解析-java高级
|
5天前
|
SQL Java 开发工具
阿里云大学考试Java中级题目及解析-java中级
阿里云大学考试Java中级题目及解析-java中级
|
5天前
|
Java 开发工具 数据库
阿里云大学考试Java初级题目及解析-java初级
阿里云大学考试Java初级题目及解析-java初级
|
5天前
|
Java
Java中的多线程编程:深入解析与实战应用
Java中的多线程编程:深入解析与实战应用
|
5天前
|
存储 安全 Java
Java并发编程中的高效数据结构:ConcurrentHashMap解析
【4月更文挑战第25天】在多线程环境下,高效的数据访问和管理是至关重要的。Java提供了多种并发集合来处理这种情境,其中ConcurrentHashMap是最广泛使用的一个。本文将深入分析ConcurrentHashMap的内部工作原理、性能特点以及它如何在保证线程安全的同时提供高并发性,最后将展示其在实际开发中的应用示例。
|
6天前
|
Java
Java输入输出流详细解析
Java输入输出流详细解析
Java输入输出流详细解析
|
6天前
|
存储 Java C++
Java集合篇之深度解析Queue,单端队列、双端队列、优先级队列、阻塞队列
Java集合篇之深度解析Queue,单端队列、双端队列、优先级队列、阻塞队列
18 0
|
8天前
|
Java
并发编程之Java 对象头的详细解析
并发编程之Java 对象头的详细解析
12 0