Get and Set Thread Name in Java Tutorial

In this section, we will learn how to set and get the name of a thread in Java.

Java Thread getName() Method

The Java getName() method is used to get the name of a thread and return that as a result.

Note that this name can be set using the `setName()` method (which you’ll learn about it later in this section) or when creating a thread using the Thread class, we can set a name for the target thread as the first or second argument of the constructor (Depending on the type of the constructor, we may need to set the first or the second argument as the name of that method).

Java Thread getName() syntax

public final String getName()

Java Thread getName() parameter

The method does not take an argument.

Return value of Thread getName() Method

The return value of this method is the name of the target thread, which will be of type String.

Java Thread getName() Method Exception:

The method does not throw an exception.

Example: using Thread getName() method in Java

public class Main {

    public static void main(String[] args) {
        System.out.println("The name of the current thread is: "+Thread.currentThread().getName());


    }

}

Output:

The name of the current thread is: main

Java Thread setName() Method

The setName() method is used to set a name for a thread in Java.

Java Thread setName() syntax

public final void setName(String name)

Java Thread setName() parameter

The method takes one argument and that is a string value that we want to set as the name of the target thread.

Return value of Thread setName() Method

The method does not return a value.

Java Thread setName() Mehtod Exception:

SecurityException: we get this exception if the current thread cannot modify the name of the target thread.

Example: using Thread setName() method in Java

public class Main {

    public static void main(String[] args) {
        System.out.println("The name of the current thread is: "+Thread.currentThread().getName());
        System.out.println("Now, changing the name of the thread using the setName() method...");
        Thread.currentThread().setName("Main-Thread");

        System.out.println("The name of the thread after changing its first name: "+ Thread.currentThread().getName());

    }

}

Output:

The name of the current thread is: main

Now, changing the name of the thread using the setName() method...

The name of the thread after changing its first name: Main-Thread

Leave a Reply