获取线程运行时的异常
在Thread类中关于处理线程运行时的异常的类有四个:
- public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh):为某个特定的线程指定UncaughtExceptionHandler;
- public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh);设置全局的UncaughtExceptionHandler ;
- public UncaughtExceptionHandler getUncaughtExceptionHandler();获取特定线程的UncaughtExceptionHandler
- public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler();获取全局UncaughtExceptionHandler
需要说下UncaughtExceptionHandler:
线程在执行单元中是不允许抛出 checked 异常的,(而且线程运行在自己的上下文中,派生它的线程没有办法直接获得它在运行出现的异常信息,但是,Java提供UncaughtExceptionHandler 接口,当线程在运行过程中出现异常时,回调 UncaughtExceptionHandler 接口,这样就知道时那个线程出现了错误,以及出现什么错误。
public class text {
// 复制一个线程组的活跃线程到thread数组中的函数
public static void Copy(ThreadGroup group) {
Thread[] list = new Thread[group.activeCount()];
group.enumerate(list);
System.out.println("----");
for (Thread a : list) {
System.out.println(a);
}
System.out.println("----");
}
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((thread,e)->{
System.out.println(thread.getName()+"发生错误");
});
ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
Thread thread = new Thread(mainGroup, () -> {
System.out.println(1/0);
}, "thread");
}
}
输出:
thread1发生异常
java.lang.ArithmeticException: / by zero
at text/bag1.text.lambda$1(text.java:35)
at java.base/java.lang.Thread.run(Thread.java:835)
- 如果该THhreadGroup有父ThreadGroup,则直接调用父Group的uncaughtException方法
- 如果父Thread中没有uncaughtException方法,则寻找全局的uncaughtException方法,
- 如果既没有父Group和全局的uncaughtException方法,则将异常的堆栈信息定向到System.err。
钩子线程的注入
1:hook线程介绍
jvm进程的退出是由于没有活跃的非守护线程,或者收到中断信号,注入hook线程后,jvm程序退出的时候会自动启动hook线程
- runtime.getRuntime().addShutdownHook(Thread t);
下面是一个最简单的hook线程的注入:
public class text {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("the hook thread2 start");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("the hook thread2 will exit");
}
});
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("the hook thread1 start");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("the hook thread1 will exit");
}
});
System.out.println("the program will exit");
}
}
输出:
the program will exit
the hook thread1 start
the hook thread2 start
the hook thread2 will exit
the hook thread1 will exit