import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/*
* 通过修改Executor生产线程的方法,Java SE5中一个新接口为Thread.UnCaughtExceptionHandler
* 这个接口允许你在每个Thread对象上都附着一个异常处理器
* 为了使用它,我们将创建一个ThreadFactory,
* 这样为每一个创建的Thread对象附着一个throw new RuntimeException();
* **/
class ExceptionThread2 implements Runnable{
@Override
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by "+t);
System.out.println("en = "+t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught "+e);
}
}
class HandlerThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
System.out.println(this + "creating new thread");
Thread t = new Thread(r);
System.out.println("created "+t);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("en = "+t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[] args){
ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
本文介绍如何在Java中利用Thread.UncaughtExceptionHandler捕获并处理线程中的未捕获异常。通过实现自定义的异常处理器,并结合使用ThreadFactory,确保每个新建线程都能注册异常处理器。示例代码展示了如何创建此类处理器并在ExecutorService中使用。
122

被折叠的 条评论
为什么被折叠?



