Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Thread Name

We have seen that we can get priority of thread as well as set priority to the thread.
Similarly, we can get a name of the thread as well as we can set name to the thread.

Get name of the thread

The method used in thread class to get name of any thread is

public final string getName()

Example

class ChildThread extends Thread
{
    public void run()
    {
        System.out.println("Child thread :: "+Thread.currentThread().getName());
    }
}

class GetNameDemo
{
    public static void main(String args[])
    {
        ChildThread c1 = new ChildThread();
        ChildThread c2 = new ChildThread();
        ChildThread c3 = new ChildThread();
        c1.start();
        c2.start();
        c3.start();
        System.out.println("Name of the main Thread :: "
                                +Thread.currentThread().getName());
    }
}

Output

Child thread :: Thread-0
Child thread :: Thread-1
Name of the main Thread :: main
Child thread :: Thread-2

By default name of a child thread starts from Thread-0, then Thread-1, then Thread-2 and so on.
Name of main thread is always main.

Note

Child thread never inherits the name of main thread. Every thread has a unique name.

Set name to the thread

A programmer can set name explicitly to each thread including main thread.

Method present in Thread class to set name is

public final void setName(string threadName)

Example

class ChildThread extends Thread
{
    public void run()
    {
        System.out.println("Default name of Child Thread :: "
                                            +Thread.currentThread().getName());
        Thread.currentThread().setName("Baby");
        System.out.println("New name of Child Thread :: "
                                            +Thread.currentThread().getName());
    }
}

class SetNameDemo
{
    public static void main(String aregs[])
    {
        ChildThread c = new ChildThread();
        c.start();
        System.out.println("Default name of main thread :: "
                                            +Thread.currentThread().getName());
        Thread.currentThread().setName("Mother");
        System.out.println("New name of main thread :: "
                                            +Thread.currentThread().getName());
    }
}

Output

Default name of main thread :: main
Default name of Child Thread :: Thread-0
New name of main thread :: Mother
New name of Child Thread :: Baby

 

Leave a reply