解决主线程无法捕获其他线程异常信息思路

Thread.UncaughtExceptionHandler 是JAVASE5的一个新接口,它允许每一个线程对象上附着一个异常处理器<br>

Thread.UncaughtExceptionHandler.uncaughtException会在线程因未捕获的异常而濒临死亡时被调用

复制代码
public class ExceptionThread implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Thread thread = Thread.currentThread();
        print("run by :" + thread);
        print("eh:" + thread.getUncaughtExceptionHandler());
        throw new RuntimeException();

    }

}
复制代码
复制代码
public class HandleThreadFactoryException implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        // TODO Auto-generated method stub
        System.out.println(this + " create new Thread");
        Thread thread = new Thread(r);
        System.out.println("created:" + thread);
        thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandle());// 为当前线程设置一个自定义异常处理器
        System.out.println("eh:" + thread.getUncaughtExceptionHandler());
        return thread;
    }

}
复制代码
复制代码
/**
 自定义捕获器
 * 
 * @date:2018年6月28日
 * @author:zhangfs
 * 
 * 
 */
public class MyUncaughtExceptionHandle implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        // TODO Auto-generated method stub
        System.out.println("异常处理器打印异常:" + e);

    }

}
复制代码
复制代码
复制代码
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool(new HandleThreadFactoryException());
        executorService.execute(new ExceptionThread());
        executorService.shutdown();

        // 默认异常捕获器
        /*
         * Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandle());
         * ExecutorService executorService = Executors.newCachedThreadPool();
         * executorService.execute(new ExceptionThread());
         * executorService.shutdown();
         */

    }

}
output:
复制代码
复制代码
复制代码

org.knowledge.muti.thread.caughtException.HandleThreadFactoryException@42a57993 create new Thread


created:Thread[Thread-0,5,main]


eh:org.knowledge.muti.thread.caughtException.MyUncaughtExceptionHandle@75b84c92


run by :Thread[Thread-0,5,main]


eh:org.knowledge.muti.thread.caughtException.MyUncaughtExceptionHandle@75b84c92


异常处理器打印异常:java.lang.RuntimeException

 
复制代码

 

 

posted @   陶朱公Boy  阅读(330)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示