Este es el código:¿Cuál es la diferencia entre "Thread.currentThread(). GetName" y "this.getName"?
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"));
}
}
y la salida es:
nombre del hilo es: Gemoji
captura java.lang.RuntimeException de Thread-1
Si yo cambió el código
System.out.println("Thread name is: " + this.getName());
a
System.out.println("Thread name is: " + Thread.currentThread().getName());
La salida cambiará a
nombre del hilo es: Hilo-1
captura java.lang.RuntimeException de Thread-1
¿Por qué?
Olvidé que 'ThreadFactory' acepta' Runnable' como param, y 'Thread' también implementa' Runnable'. Gracias por tu ayuda. – PeaceMaker