多线程(6)- Hook线程与线程异常捕获
前言
Hook钩子,线程异常扩展:
概念
- UncaughtExceptionHandler: 线程在执行单元(run部分)是不允许抛出异常的,而且线程运行在自己的上下文中,派生它的线程将无法直接获得它运行中出现的异常信息,对此JAVA提供了UncaughtExceptionHandler接口,当线程运行中出现异常,会回调UncaughtExceptionHandler接口,告诉是哪个线程出现什么错误。
- 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