/**
*
* @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编程思想-并发之线程异常处理器
最新推荐文章于 2017-12-20 19:00:03 发布