Java Naming Thread
Each thread in Java has its own name which is set by the JVM by default. Although there are many other attributes associated to the thread like: id, priority etc.
we can get name of a thread by calling getName()
method of Thread class. If we wish to set new name of the thread then setName() method can be used. Both methods belongs to Thread class and even we can set name of thread by passing into constructor during creating object. Lets understand by the examples.
Syntax of the two methods is given below.
Example: Fetch Thread Name
lets first fetch the thread name set by the JVM. It is default name so initially we cannot predict it.
thread running… thread name: Thread-0
we can also use static currentThread() method of Thread class. it returns thread name, priority etc. it is static method so object is not require to call it. See the below example.
Example: Thread.currentThread()
In this example, we are using currentThread method of Thread class to get name of the thread.
thread running… Thread name: Thread[Thread-0,5,main]
Example: Setting Name
In this example, we are using setName() method to set name of the thread and getName() method to get name of the thread.
thread running… Thread Name: mythread
Example : Setting Name using constructor
We can set name of a thread by passing through the constructor. Thread class constructor that allows a string type argument can be used to set name. See the below example.
thread running… Thread Name: mythread
Since we are extending the Thread class so we call its constructor through the super call and passed thread name to the MyThread class.
Example: Setting Name
We can directly pass the thread name to the constructor by creating thread class object.
thread running… Thread Name: mythread
In this topic, we learned to fetch thread name using getName()
and currentThread()
methods, and to set the name using setName() method and passing name to the constructor.