How do I set and get the name of a thread?

You can assign a name to thread instance by using the setName() method and get the name of the thread using the getName() method. The naming support is also available as a constructor of the Thread class such as Thread(String name) and Thread(Runnable target, String name).

package org.kodejava.example.lang;

public class ThreadNameDemo extends Thread {
    public ThreadNameDemo() {

    public ThreadNameDemo(String name) {

    public void run() {
        // Call getName() method to get the thread name of this
        // thread object.
        System.out.println("Running [" + this.getName() + "]");

    public static void main(String[] args) {
        Thread thread1 = new ThreadNameDemo();

        Thread thread2 = new ThreadNameDemo("DOG");


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵

Leave a Reply