这是代码:
输出将变为:
这是代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
class UnCatchExceptionThread extends Thread{
public UnCatchExceptionThread(String name){
this.setName(name);
}
@Override
public void run() {
System.out.println("Thread name is: " + this.getName());
throw new RuntimeException();
}
}
class UnCatchExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("catch " + e + " from " + t.getName());
}
}
class HandlerFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(new UnCatchExceptionHandler());
return t;
}
}
public class CaptureException {
public int i;
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(new HandlerFactory());
exec.execute(new UnCatchExceptionThread("Gemoji"));
}
}
输出结果为:
线程名称是:Gemoji
捕获来自Thread-1的java.lang.RuntimeException异常
如果我更改了代码
System.out.println("Thread name is: " + this.getName());
为了
System.out.println("Thread name is: " + Thread.currentThread().getName());
输出将变为:
线程名称为:Thread-1
从Thread-1捕获java.lang.RuntimeException异常
为什么?
ThreadFactory
接受Runnable
作为参数,而且Thread
也实现了Runnable
。感谢您的帮助。 - PeaceMaker