Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "Thread.currentThread().getName" and "this.getName"?

This is the code:

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"));
    }

}

And the output is:

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

If I changed the code

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

to

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

The output will change to

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

Why?

like image 472
PeaceMaker Avatar asked Dec 28 '11 14:12

PeaceMaker


1 Answers

I assume that at one moment, the UnCatchExceptionThread is passed to your HandlerFactory.newThread() method, and the thread returned by this method is executed. If so, you create a new thread with no name, that executes the runnable passed as argument. The runnable is the UnCatchExceptionThread instance, but the thread that is executing is the new Thread(r).

So, inside the Runnable run method, this is the instance of UnCatchExceptionThread, and has the name you gave him. But the current thread is new Thread(r), which has a default name.

like image 125
JB Nizet Avatar answered Nov 03 '22 13:11

JB Nizet