Pea*_*ker 7 java multithreading
这是代码:
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
线程名称是:Gemoji
从Thread-1捕获java.lang.RuntimeException
如果我改变了代码
System.out.println("Thread name is: " + this.getName());
Run Code Online (Sandbox Code Playgroud)
至
System.out.println("Thread name is: " + Thread.currentThread().getName());
Run Code Online (Sandbox Code Playgroud)
输出将更改为
线程名称是:Thread-1
从Thread-1捕获java.lang.RuntimeException
为什么?
我假设在某一时刻,UnCatchExceptionThread被传递给您的HandlerFactory.newThread()方法,并执行此方法返回的线程.如果是这样,则创建一个没有名称的新线程,该线程执行作为参数传递的runnable.runnable是UnCatchExceptionThread实例,但正在执行的线程是new Thread(r).
因此,在Runnable run方法中,this是UnCatchExceptionThread的实例,并且具有您给他的名称.但是当前的线程是new Thread(r),它有一个默认名称.