Home »
Java programming language
Java Thread Class final void setName(String thread_name) method with Example
Java Thread Class final void setName(String thread_name) method: Here, we are going to learn about the final void setName(String thread_name) method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 31, 2019
Thread Class final void setName(String thread_name)
- This method is available in package java.lang.Thread.setName(String thread_name).
- This method is used to sets the name of this thread.
- This method is not static so this method is accessible with Thread class object it is not accessible with the class name.
- This method is final so we can't override this method in our program.
- The return type of this method is void so it does not return anything.
- This method does not raise an exception if this thread can't modify.
Syntax:
final void setName(String thread_name){
}
Parameter(s):
We pass only one object as a parameter in the method of the Thread and the parameter is the new name of this thread.
Return value:
The return type of this method is String, it returns the name of this thread as a string.
Java program to demonstrate example of setName() method
/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class SetThreadName extends Thread {
// Override run() of Thread class
public void run() {
System.out.println("The priority of this thread is : " + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// Creating an object of SetThreadName class
SetThreadName st_name = new SetThreadName();
System.out.println("The old name of this thread is " + " " + st_name.getName());
// We are setting the name of the thread SetThreadName
st_name.setName("SetThreadName");
/* Calling start() method with SetThreadName class
object of Thread class
*/
st_name.start();
/* By using getName() method to return the name of
this thread [SetThreadName ]
*/
System.out.println("The new name of this thread is " + " " + st_name.getName());
}
}
Output
E:\Programs>javac SetThreadName.java
E:\Programs>java SetThreadName
The old name of this thread is Thread-0
The new name of this thread is SetThreadName
The priority of this thread is : 5