java 多线程异常捕获

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());
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值