Java捕获ThreadPoolExecutor内部线程异常的四种方法

2025-03-14 01:50

本文主要是介绍Java捕获ThreadPoolExecutor内部线程异常的四种方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感...

方案 1

使用 execute + try-catch 记录异常

import Java.util.concurrent.*;
 
public class ThreadPoolExceptionDemo {
    public static vwww.chinasem.cnoid main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4, 10, TimeUnit.SECONDS,
                new LinkedblockingQueue<>(),
                new ThreadFactory() {
                    private int count = 1;
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "custom-thread-" + count++);
                    }
                });
 
        executor.execute(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " 正在执行任务");
                throw new RuntimeException("任务异常");
            } catch (Exception e) {
                System.err.println("线程 " + Thread.currentThread().getName() + " 捕获异常: " + e.getMessage());
                e.printStackTrace();
            }
        });
 
        executor.shutdown();
    }
}

方案 2

使用 submit + Future

submit() 方法返回 Future,可以通过 get() 方法捕获异常:

public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);
 
    Future<?> future = executor.submiwww.chinasem.cnt(() -> {
        System.out.println(Thread.currentThread().getName() + " 正在执行任务");
        throw new RuntimeException("任务异常");
    });
 
    try {
        future.get(); // get() 会抛出 ExecutionException
    } catch (InterruptedException | ExecutionException e) {
        System.err.println("线程 " + Thread.currentThread().getName() + " 捕获异常: " + e.getCause().getMessage());
        e.printStackTrace();
    }
 
    executor.shutdown();
}

注意

  • get() 方法会阻塞主线程直到任务完成。
  • ExecutionException 的 getCause() 方法可以获取原始异常。

方案 3

自定义 UncaughtExceptionHandler

可以为线程设置 UncaughtExceptionHandler,当 Runnable 没有捕获异常时,ThreadPoolExecutor 也不会吞掉异常:

public class ThreadPoolWithExceptionHandler {
    public static void main(String[] args) {
        ThreadFactory threadFactory = r -> {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler((thread, throwable) -> {
                System.err.println("线程 " + thread.getName() + " 发生异常: " + throwable.getMessage());
                throwable.printStackTrace();
            });
            returnChina编程 t;
        };
 
        ExecutorService executor = new ThreadPoolExecutor(
                2, 4, 10, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                threadFactory
        );
 
        executor.execute(() -> {
            System.out.println(Thread.currentThread().getName() + " 正在执行任务");
            throw new RuntimeException("任务异常");
        });
 
        executor.shutdown();
    }
}

方案 4

重写 afterExecute 方法

如果你要在 ThreadPoolExecutor 内部直接处理异常,可以继承 ThreadPoolExecutor 并重写 afterExecute()

class CustomThreadPoolExecutor extends ThreadPoolExecutor {
    public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
 
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                ((Future<?>) r).get(); // 获取任务结果,捕获异常
            } catch (InterruptedException | ExecutionException e) {
                t = e.getCause();
            }
        }
        if (t != null) {
            System.err.println("线程 " + Thread.currentThread().getName() + " 发生异常: " + t.getMessage());
            t.printStackTrace();
        }
    }
}
 
public class ThreadPoolAfterExecuteDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new CustomThreadPoolExecutor(2, 4, 10, TimeUnit.SECOChina编程NDS, new LinkedBlockingQueue<>());
 
        executor.submit(() -> {
            System.out.println(Thread.currentThread().getName() + " 正在执行任务");
            throw new RuntimeException("任务异常");
        });
 
        executor.shutdown();
    }
}

结论

方案适用场景缺点
try-catch 手动处理适用于 execute()代码侵入性强,所有任务都要加 try-catch
Future.get() 捕获异常适用于 submit()get() 会阻塞主线程
UncaughtExceptionHandler适用于 exe编程China编程cute()不能捕获 submit() 提交的异常
afterExecute() 适用于 execute() 和 submit()需要继承 ThreadPoolExecutor

推荐:

  • 任务内部 try-catch 适用于 execute()
  • Future.get() 适用于 submit()
  • 统一异常处理建议使用 afterExecute() 或 UncaughtExceptionHandler

到此这篇关于Java捕获ThreadPoolExecutor内部线程异常的四种方法的文章就介绍到这了,更多相关Java ThreadPoolExecutor异常内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Java捕获ThreadPoolExecutor内部线程异常的四种方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153735

相关文章

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Pytest多环境切换的常见方法介绍

《Pytest多环境切换的常见方法介绍》Pytest作为自动化测试的主力框架,如何实现本地、测试、预发、生产环境的灵活切换,本文总结了通过pytest框架实现自由环境切换的几种方法,大家可以根据需要进... 目录1.pytest-base-url2.hooks函数3.yml和fixture结论你是否也遇到过

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu