Open In App

Java Naming a Thread and Fetching Name of Current Thread

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

A thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java.

Methods to Set the Thread Name

There are two ways by which we can set the name either be it directly or indirectly which we will be peeking through.

  1. Creating the thread and Passing the thread's name (Direct method)
  2. Using the setName() method of Thread class (Indirect Method)

1. Using Constructor to Set the Thread Name (Direct Method)

It is a direct method of naming threads in Java, each thread has a name that is: Thread-0, Thread-1, Thread-2,....so on. So, let us check the direct method to set the name of the Thread.

Example: Setting the thread name at the time of creation and also bypassing the thread's name as an argument.


Output
Thread 1: geek1
Thread 2: geek2
Thread is running..
Thread is running..


2. Using setName() method of Thread class (Indirect Method)

We can set(change) the thread's name by calling the setName method on that thread object. It will change the name of a thread.

Syntax: 

public final void setName(String name)

Parameter: A string that specifies the thread name 

Example:


Output
Thread 1: Thread-0
Thread 2: Thread-1
Thread is running..
Thread names after changing the thread names
New Thread 1 name:  geeksforgeeks
New Thread 2 name: geeksquiz
Thread is running..

How to Fetch the Name of the Current Thread?

Now let us dwell on fetching the name of the current thread. We can fetch the current thread name at the time of creating the thread and bypassing the thread’s name as an argument. 

Syntax: 

public static Thread currentThread()

  • Package: java.lang.Thread
  • Return Type: It returns a reference to the currently executing thread.

Example:


Output
Fetching current thread name.
Thread-0
Fetching current thread name.
Thread-1

Thread Naming (Java)
Article Tags :
Practice Tags :

Similar Reads