线程捕获异常的方式
来源:互联网 发布:培训矩阵 含义 编辑:程序博客网 时间:2024/05/21 11:28
只需要修改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); }}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()); }}
阅读全文