How to get and set name of a thread in Java?

Learn: how to get and set name of a thread in Java? Define getName() and setName(String str) methods in java? How to replace name of a Thread in Java?
By Preeti Jain Last updated : January 26, 2024

Every Thread in java has some unique name. It may be provided by the developer (user defined) or default name (if user not defined) generated by JVM (JVM defined).

Getting Thread Name

To get the thread name in Java, you can use the Thread.currentThread().getName(); method.

Syntax

public final String Thread.currentThread().getName();

Example

class GetName{
    public static void main(String[] args){
        String tn = Thread.currentThread().getName();
        System.out.println(tn);
    }
}

Output:

E:\javasource>java GetName
main

Setting Thread Name

To set the thread name in Java, you can use the Thread.currentThread().setName(); method.

Syntax

public final void Thread.currentThread().setName(String name);

Example

class SetName{
    public static void main(String[] args){
        Thread.currentThread().setName("main is changed to parent");
        System.out.println(Thread.currentThread().getName());
    }
}

Output

E:\javasource>java SetName
main is changed to parent

Here, Thread.currentThread().setName("main is changed to parent") - Current thread is main thread so name of main is replaced with main is changed to parent by the method setName(String str)


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.