这是代码:
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"));
}
}
输出为:
如果我更改了代码
System.out.println("Thread name is: " + this.getName());
到
System.out.println("Thread name is: " + Thread.currentThread().getName());
输出将更改为
为什么?
最佳答案
我假设有一次,UnCatchExceptionThread传递给了HandlerFactory.newThread()
方法,并且执行了该方法返回的线程。如果是这样,您将创建一个没有名称的新线程,该线程将执行作为参数传递的runnable。可运行的是UnCatchExceptionThread实例,但是正在执行的线程是new Thread(r)
。
因此,在Runnable run
方法中,this
是UnCatchExceptionThread的实例,并具有您为其指定的名称。但是当前线程是new Thread(r)
,它具有默认名称。