0 0

Thread.currentThread().getName 和 this.getName有什么区别?5

直接上代码吧
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"));
	}

}


输出如下:
引用

Thread name is: Gemoji
catch java.lang.RuntimeException from Thread-1

而把
System.out.println("Thread name is: " + this.getName());

换成
System.out.println("Thread name is: " + Thread.currentThread().getName());

之后,输出就变成了:
引用

Thread name is: Thread-1
catch java.lang.RuntimeException from Thread-1


这是为什么呢?
2011年12月28日 21:56
目前还没有答案

相关推荐

Global site tag (gtag.js) - Google Analytics