Ameet
Ameet

Reputation: 341

name of main thread

Can we able to change the name of main thread? and in main method

Thread t = Thread.currentThread();  
System.out.println(t);

It prints :

Thread[main,5,main]

- here first thread name , second priority, third is thread group to which current thread belongs to.

Is it right?

What is thread group the third parameter?

Upvotes: 5

Views: 9229

Answers (2)

Bhupendra Khilrani
Bhupendra Khilrani

Reputation: 1

The correct way of getting the name of the current thread is

System.out.println("Name of Thread is " + Thread.currentThread().getName());

where currentThread() is a static method of the Thread class, which refers to current thread in execution; and getName() is the function which gives the name of that thread.

Upvotes: -2

Peter Lawrey
Peter Lawrey

Reputation: 533492

From the Javadoc for Thread

public final void setName(String name)

Changes the name of this thread to be equal to the argument name.

and

public String toString()

Returns a string representation of this thread, including the thread's name, priority, and thread group.


Thread t = Thread.currentThread();
System.out.println(t);
t.setName("new thread name");
System.out.println(t);

prints

Thread[main,5,main]
Thread[new thread name,5,main]

To change the ThreadGroup's name you could use reflection but that's unlikely to be a good idea.

Upvotes: 14

Related Questions