1.捕获线程的异常只需要修改Executor产生线程的方式,即为每一个线程添加一个实现了Thread.UncaughtExceptionHandler接口的异常处理器来捕获线程发生的异常,出现异常之后在捕捉异常中在重新开启线程即可,例子如下:(Thinking in java 中demo)
class ExceptionThread2 implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by" + t);
System.out.println("eh =" + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught...." + e);
//重新开启新的线程,继续执行业务逻辑代码
ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
class HandlerThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
// 将当前线程绑定异常处理器
System.out.println(this + "创建线程");
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("eh =" + thread.getUncaughtExceptionHandler());
return thread;
}
}
public class ExceptionThread {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}