多线程(6)- Hook线程与线程异常捕获


前言

Hook钩子,线程异常
扩展:

概念

  1. UncaughtExceptionHandler: 线程在执行单元(run部分)是不允许抛出异常的,而且线程运行在自己的上下文中,派生它的线程将无法直接获得它运行中出现的异常信息,对此JAVA提供了UncaughtExceptionHandler接口,当线程运行中出现异常,会回调UncaughtExceptionHandler接口,告诉是哪个线程出现什么错误。
  2. Hook钩子:作为程序运行结束时的线程,处理后续工作

1、UncaughtExceptionHandler

API
//特定线程设置全局的UncaughtExceptionHandler 
public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
//设置全局的UncaughtExceptionHandler 
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 
//获取全局的UncaughtExceptionHandler 
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
   
   
        return defaultUncaughtExceptionHandler;
    }
//获取特定线程的UncaughtExceptionHandler 
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
   
   
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;
    }
dispatchUncaughtException-异常回调
//仅由JVM调用此方法处理异常
/**
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     */
private void dispatchUncaughtException(Throwable e) {
   
   
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

2、获取线程运行时异常

/**
     * 使用钩子 处理异常
     */
    private static void uncaughtException() {
   
   
        Thread.setDefaultUncaughtExceptionHandler((t,e)->{
   
   
            System.out.println(t);
            e.printStackTrace();
        });
        new Thread(()->{
   
   
            try {
   
   
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
   
   
                e.printStackTrace();
            }
            System.out.println(1/0);
        },"thread_uncaught").start
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值