Master java skills

Naming a thread

When we create threads, we can also give a custom name to them. It can be done using setName(String name) method. When we don’t give any names to threads, they are given default names like Thread-0, Thread-1, Thread-2 etc.

Similarly, we can get name of any thread using method getName().

Let’s see few examples of these methods.

Thread.currentThread()

Thread.currentThread() is a static method of Thread class. It returns the currently running thread example. There are many methods like getName(), getId(), getPriority() etc, which give information about currently running thread.

package com.javatrainingschool;

public class ThreadNamingExample {

	public static void main(String[] args) {

		Thread t = new Thread() {
			public void run() {
				System.out.println("Thread executed");
				System.out.println("Currently running thread name : " +
                                                                    Thread.currentThread().getName());
			}
		};
		t.start();
	}
}
Output :
Thread executed
Currently running thread name : Thread-0

Naming a thread – setName(String name) method

A thread can be given a name in two ways.

  1. At the time of creation by passing name in the Thread constructor
  2. After thread creation, by using setName(String name) method

Below is the example where we are passing thread name in the Thread constructor

package com.javatrainingschool;

public class ThreadNamingExample {

	public static void main(String[] args) {

		Thread t = new Thread("My User Thread") {
			public void run() {
				System.out.println("Thread executed");
				System.out.println("Currently running thread name : " +  
                                                                      Thread.currentThread().getName());
			}
		};
		t.start();
	}
}
Output :
Thread executed
Currently running thread name : My User Thread

In the below example, we will not give any name while constructing the thread object, but use setName(String name) method to set the name.

package com.javatrainingschool;

public class ThreadNamingExample {

	public static void main(String[] args) {

		Thread t = new Thread() {
			public void run() {
				System.out.println("Thread executed");
				System.out.println("Currently running thread name : " +
                                                                      Thread.currentThread().getName());
			}
		};
		t.setName("My User Thread");
		t.start();
	}
}
Output :
Thread executed
Currently running thread name : My User Thread