What is 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 result:

Theme Name: 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 be changed to

Thread Title: Thread-1
catch java.lang.RuntimeException from Thread-1

Why?

+6
source share
2 answers

I assume that at one point, 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 runs runnable, passed as an argument. Runnable is an instance of UnCatchExceptionThread, but the executable thread is new Thread(r) .

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

+6
source

The executing service creates a thread "Thread-1" to run the run command from the given runnable. Thus, the name of the thread object "Gemoji" is not the actual thread that is running.

0
source

Source: https://habr.com/ru/post/904603/


All Articles