package concurrency;
import static net.mindview.util.Print.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/*
* 捕获线程中的异常。
* 修改Executor产生线程的方式.Thread.UncaughtExceptionHandler是JavaSE5的新接口,
* 它允许你在每个Thread对象上都附着一个异常处理器。Thread.UncaughtExceptionHandler.uncaughtException()会在线程因未捕获
* 的异常而临近死亡时被调用。为了使用它,我们讲一个新类型的ThreadFactory,它将在每个新创建的Thread对象上附着一个Thread.UncaughtExceptionHandler
* */
class ExceptionThread2 implements Runnable{
public void run(){
Thread t=Thread.currentThread();
print("run() by "+t);
print("en ="+t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
public void uncaughtException(Thread t, Throwable e) {
print("caught "+e);
}
}
class HandlerThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r){
print(this+" creating new Thread");
Thread t=new Thread(r);
print("created "+t);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("eh= "+t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[]args){
ExecutorService exec=Executors.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
java 多线程异常捕获
最新推荐文章于 2024-07-10 21:37:49 发布