What is the thread.getName() function in Java?

In the java.lang package, Thread is a major class in Java in which a multithreading system is based. In Java, we can use it to process threads with or without the Runnable interface.

The getName() method is used to get the name of a thread. We can call this method through thread class instance.

Syntax


String getName()

Parameters

This function takes no parameters.

Return value

Thread_Name: it returns a string containing this thread name.

Example

As highlighted, we can call the getName() method to extract the thread name through its instance or using this (the current object).

// Load Thread class from
// java.lang package
import java.lang.Thread;
// main program
public class EdPresso {
public static void main(String[] args)
{
System.out.println("Main thread Name: "
+ Thread.currentThread().getName());
Thread thread = new Thread(new EdPresso().
new Runnabledemo());
thread.start();
}// runnable interface class
private class Runnabledemo implements Runnable {
public void run()
{
System.out.println("In run() Thread Name: " + Thread.currentThread().getName());
}
}
}

Free Resources