Prizoff
Prizoff

Reputation: 4575

How to set name to the thread?

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

Upvotes: 25

Views: 47532

Answers (6)

Ranjith
Ranjith

Reputation: 181

Yes, you can set a name to thread using:

Thread.getCurrentThread().setName(threadName);

Upvotes: 2

AAnkit
AAnkit

Reputation: 27549

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

Upvotes: 40

Chintan Raghwani
Chintan Raghwani

Reputation: 3370

Try this:

Thread thread = new Thread("MyImportThread") {
      public void run(){    
        // code
      }
   };
   thread.start();
   System.out.println(thread.getName());

Upvotes: 3

Simon Dorociak
Simon Dorociak

Reputation: 33505

Did you try something like this?

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

Have look also at Threads reference especially at constructors.

Upvotes: 7

Kevin Coppock
Kevin Coppock

Reputation: 134664

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

Upvotes: 8

Jonathan Naguin
Jonathan Naguin

Reputation: 14766

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?

Upvotes: 3

Related Questions