Thread.UnCaughtExceptionHandler接口,为每一个Thread对象创建一个异常处理器
2015-10-17 12:11
471 查看
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{
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
}
class HandlerThreadFactory implements ThreadFactory{
}
public class CaptureUncaughtException {
}
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()); }
}
相关文章推荐
- CSS控制字体
- 1691: [Usaco2007 Dec]挑剔的美食家
- 二维矩阵的初始化
- linux安装redis服务以及php redis扩展
- 【Foundation-18-1】NSDate - 创建
- IScroll 无法上下滚动问题
- 好网址
- POJ 2385 Apple Catching(01背包)
- 程序员如何打扫卫生并向老婆汇报
- 安装brew
- POJ-2109
- Java面试题目
- apache2: bad user name ${APACHE_RUN_USER} 解决方法
- spring如何解析通配符路径
- CSS 颜色单位
- 学习内核驱动程序的错误及其解决方案的出现,
- 【Mockplus教程】如何批量修改组件属性
- 2015年10月15日项目经理中项作业(质量管理与人力资源管理)
- c语言全局变量和局部变量问题汇总
- vim翻页命令总结