25

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

Community
  • 1
  • 1
Prizoff
  • 4,486
  • 4
  • 41
  • 69
  • yep.. it was a very dumb question, but I was confused a little of how to do it... :) thx for the answers, I even do not know which of them chose as correct :) – Prizoff Jul 12 '12 at 18:01

6 Answers6

40

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

pdoherty926
  • 9,895
  • 4
  • 37
  • 68
AAnkit
  • 27,299
  • 12
  • 60
  • 71
8

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

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
7

Did you try something like this?

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

Have look also at Threads reference especially at constructors.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
3

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?

Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
3

Try this:

Thread thread = new Thread("MyImportThread") {
      public void run(){    
        // code
      }
   };
   thread.start();
   System.out.println(thread.getName());
Chintan Raghwani
  • 3,370
  • 4
  • 22
  • 33
2

Yes, you can set a name to thread using:

Thread.getCurrentThread().setName(threadName);
peterh
  • 11,875
  • 18
  • 85
  • 108
Ranjith
  • 181
  • 2
  • 9