第一个:子线程类
public class ThreadExceptionRunner implements Runnable {
@Override
public void run() {
throw new RuntimeException(
"error!"
);
}
}
第二步:主线程类 在最后面有我自定义的两个class是作为配置用的,有解释
public class DemoThread {
public static void main(String[] args) {
Thread thread = new Thread(new ThreadExceptionRunner());
thread.start();
System.out.println("=================================");
//3:通过Executors.newCachedThreadPool把第二步骤的类加进去,这样 你就可以捕获自定义的异常啦,孩子,去用吧
ExecutorService exec = Executors.newCachedThreadPool(new HandleThreadFactory());
exec.execute(new ThreadExceptionRunner());
exec.shutdown();
}
}
//1:首先 实现一个 Thread.UccaugthExceptionHandler
//在里面自定义你要 捕获的的格式
class MyUncaughtExceptionHandle implements Thread.UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("zidingyi"+e);
}
}
//2:其次 实现 ThradFactory 把自定义的格式加进去
class HandleThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
System.out.println("create thread t");
Thread thread=new Thread(r);
System.out.println("set uncaughtException for t");
thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandle());
return thread;
}
}