How to Get Current Thread in Java Tutorial

In this section, we will learn how to get a reference to the current thread that is running in Java.

Java Thread currentThread() Method

The currentThread() method is a static type method that belongs to the Thread class and it will return a reference to the thread that is currently executing.

currentThread() syntax

public static Thread currentThread()

currentThread() parameters

The method does not take a parameter.

currentThread() Return Value

The return value of this method is a reference to the currently executing thread.

currentThread() Exception:

The method does not throw an exception.

Example: using currentThread() method

public class Main {

    public static void main(String[] args) {
        System.out.println("The name of the current thread is: "+Thread.currentThread().getName());
        System.out.println("Now, changing the name of the thread using the setName() method...");
        Thread.currentThread().setName("Main-Thread");

        System.out.println("The name of the thread after changing its first name: "+ Thread.currentThread().getName());

    }

}

Output:

The name of the current thread is: main

Now, changing the name of the thread using the setName() method...

The name of the thread after changing its first name: Main-Thread

Leave a Reply