How to set name to the thread?

42,947

Solution 1

You can easily pass a thread name in Its Constructor, like:

Thread foo = new Thread("Foo");

... or by calling Thread#setName:

public final void setName (String threadName)

Sets the name of the Thread.

as thread.setName("Thread-11"); or like Thread.currentThread().setName("Thread-11");

Solution 2

Check the Thread constructors, there are a few with a String name parameter. Or you can call setName(String) on an existing Thread.

Solution 3

Did you try something like this?

Thread.currentThread().setName("MyThread");

Have look also at Threads reference especially at constructors.

Solution 4

The class Thread has a method for that:

public final void setName (String threadName)

Since: API Level 1
Sets the name of the Thread.

Did you try it?

Solution 5

Try this:

Thread thread = new Thread("MyImportThread") {
      public void run(){    
        // code
      }
   };
   thread.start();
   System.out.println(thread.getName());
Share:
42,947
Prizoff
Author by

Prizoff

Updated on July 09, 2022

Comments

  • Prizoff
    Prizoff almost 2 years

    Is there a way to set a friendly name to a thread in code?

    For example, I want the thread with name Thread-11 on the image was named something like 'MyImportThread'.

    example-threads