Thread类
1、dispatchUncaughtException()方法应该是在native层触发,这个时候调用了getUncaughtExceptionPreHandler(),它的优先级比其他的UncaughtExceptionHandler要高
public final void dispatchUncaughtException(Throwable e) {
1、UncaughtExceptionPreHandle优先级高
Thread.UncaughtExceptionHandler initialUeh =
Thread.getUncaughtExceptionPreHandler();
if (initialUeh != null) {
try {
initialUeh.uncaughtException(this, e);
} catch (RuntimeException | Error ignored) {
// Throwables thrown by the initial handler are ignored
}
}
2、调用UncaughtExceptionHandler
getUncaughtExceptionHandler().uncaughtException(this, e);
}
2、如果设置了uncaughtExceptionHandler,则用。否则用group(ThreadGroup类型)
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
ThreadGroup类
1、Thread类的构造方法,定义了ThreadGroup怎么取值
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
ThreadGroup默认为空,取当前线程的ThreadGroup
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
Thread parent = currentThread();
if (g == null) {
g = parent.getThreadGroup();
}
...
this.group = g;
...
}
2、在ThreadGroup类的uncaughtException()方法,如果parent不为空,则直接调用它的uncaughtException(),否则,调用默认的handler
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}