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

相关文章

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.