๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Naming Thread Methods with Example  


Introduction
  • Every thread in a Java program has a unique name.
  • Whenever we create a new thread, the JVM automatically assigns a default name such as Thread-0, Thread-1, Thread-2 and so on.
  • Use :-
    • Identify threads by name for logging and debugging purposes.
    • Give meaningful names to threads in multi-threaded applications.
    • Track thread execution in large concurrent programs.
  • To work with thread names, Java provides two important methods in the Thread class:
    1. public final String getName()
      • Used to retrieve the current name of a thread.
    2. public final void setName(String name)
      • Used to assign or change the name of a thread.
  • Program :-
    class MyThread extends Thread
    {
        @Override
        public void run()
        {
            System.out.println("Thread running: " + getName());
    
            // Change the thread name
            setName("Updated-Thread");
            System.out.println("Thread renamed to: " + getName());
        }
    }
    
    public class ThreadNameDemo
    {
        public static void main(String[] args)
        {
            MyThread t1 = new MyThread();
            t1.setName("Initial-Thread");
    
            System.out.println("Before start: " + t1.getName());
    
            t1.start();
    
            // Main thread
            System.out.println("Main thread: " + Thread.currentThread().getName());
        }
    }
  • Other key points :-
    • Both methods are final, cannot be overridden.
    • Useful for logging and debugging multi-threaded applications.
    • Thread names can be set either via setName() or constructor Thread(String name).
    • Default thread names are like Thread-0, Thread-1, etc., if not set explicitly.