Thread getName() method in java

Method declaration – public String getName().

This method returns the Thread name.

package multithreading;

public class ThreadGetNameExample {
	public static void main(String[] args) {
		System.out.println("Thread name is :- "+Thread.currentThread().getName());
	}
}

Output is –┬áThread name is :- main

Inside getName() method we are returning name variable which is defined as volatile.

class Thread {

	private volatile String name;

	public final String getName() {
		return name;
	}
}

Let’s see another example where we will define a custom thread.


package multithreading;

public class ThreadExample extends Thread {

	public static void main(String[] args) {
		Thread thread1 = new Thread() {
			public void run() {
				System.out.println("Using Thread class "+Thread.currentThread().getName());
			}
		};
		
		thread1.start();
		
		Runnable r = new Runnable() {
			public void run() {
				System.out.println("Using Runnable interface "+Thread.currentThread().getName());
			}
		};
 
		
		Thread thread2 = new Thread(r);
		thread2.start();
		
	}

}

Output is –


Using Thread class Thread-0
Using Runnable interface Thread-1