/**
*
* @author wenruo
* @date 2017-8-7
*
*/
class ExceptionThread implements Runnable{
@Override
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{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(t.getName()+"---->"+e);
}
}
class HandlerThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
System.out.println(this+" creating new Thread");
Thread thread=new Thread(r);
System.out.println(" created "+thread);
//未捕获的异常通过uncaughtException来捕获
//专有的异常处理器的优先级高于默认异常处理器
thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println(" eh="+thread.getUncaughtExceptionHandler());
return thread;
}
}
public class ThreadExceptionTest {
public static void main(String[] args) {
//设置默认未捕获异常处理器
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
ExecutorService service=Executors.newCachedThreadPool(new HandlerThreadFactory());
service.execute(new ExceptionThread());
}
}
java编程思想-并发之线程异常处理器
最新推荐文章于 2025-05-29 22:27:42 发布
本文介绍了一个Java程序中如何自定义线程工厂和未捕获异常处理器来处理线程运行时产生的异常。通过创建ExceptionThread类抛出异常,并使用MyUncaughtExceptionHandler类捕获这些异常进行处理。
729

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



