In Java, each thread has a unique name that helps in identifying it during execution. Java also provides the currentThread() method to access the currently executing thread. In this chapter, we will learn how to name threads and work with the current thread in Java.
The Thread class provides methods to change and get the name of a thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName() method.
The syntax of setName() and getName() methods are given below:
We can also set the name of a thread directly when we create a new thread using the constructor of the class.
The following example demonstrates how to assign a custom name to a thread using the setName() method.
Output:
Name of t1:Thread-0 Name of t2:Thread-1 After changing name of t1:Sonoo Jaiswal running... running...
You can also set the name of a thread at the time of the creation of a thread, without using the setName() method.
The following example demonstrates how a thread is automatically assigned a default name when the setName() method is not used.
Output:
Thread - 1: JavaTpoint1 Thread - 2: JavaTpoint2 The thread is executing.... The thread is executing....
The currentThread() method returns a reference to the currently executing thread and it is commonly used to obtain the thread's name, priority, and state.
The following is the syntax to get the current thread i.e., currentThread() method:
The following example demonstrates how the currentThread() method is used to obtain information about the currently executing thread.
Output:
Thread-0 Thread-1
We request you to subscribe our newsletter for upcoming updates.