Learnitweb

How can you access the current thread in Java?

Sometimes we need to know about the currently executing thread. For example, for debugging purposes we want information about current Thread. Current thread here means the currently executing thread object in Java. currentThread() method returns a reference to the currently executing thread object.

public static Thread currentThread()

In the following example, currently executing thread is ‘main’ thread. We can get the currently executing thread reference by using currentThread() method. Using current thread reference, we can get other information about thread like ID and name of thread.

public class Test {
	public static void main(String args[]) {
		Thread t = Thread.currentThread();
		System.out.println("Current Thread: " + t);
		System.out.println("Current Thread Id: "+ t.getId());
		System.out.println("Current Thread Name: " + t.getName());
		
	}
}

Output

Current Thread: Thread[main,5,main]
Current Thread Id: 1
Current Thread Name: main