run()外部捕获run()内未捕获的异常

阅读更多
package test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class ExcetptionThread2 implements Runnable{

	@Override
	public void run() {
		Thread t=Thread.currentThread();
		System.out.println("run() by"+t);
		System.out.println("eh="+t.getUncaughtExceptionHandler());
		throw new NullPointerException();
		
		
	}
	
}
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) {
		System.out.println(this+"creating new Thread");
		Thread t=new Thread(r);
		System.out.println("created"+t);
		t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
		System.out.println("eh="+t.getUncaughtExceptionHandler());
		
		return t;
	}
	
}
public class CaptureUncaughtException {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService exec=Executors.newCachedThreadPool(new HandlerThreadFactory());
		exec.execute(new ExcetptionThread2());
	}

}

 

你可能感兴趣的:(thread,Java)