Write a Java program to get information of the current executing thread


The code you've provided is correct and demonstrates how to obtain various information about the current executing thread in Java. It uses methods provided by the Thread class to access information such as the thread's name, ID, priority, state, daemon status, liveness, and interruption status. Your code is a useful example of how to retrieve and display thread information in a Java program. Here's a breakdown of what the code does:

  • Thread.currentThread(): This method returns a reference to the currently executing thread.
  • getName(): This method returns the name of the thread.
  • getId(): This method returns the unique identifier of the thread.
  • getPriority(): This method returns the priority of the thread. Thread priorities range from 1 (lowest) to 10 (highest).
  • getState(): This method returns the current state of the thread. The possible states include NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
  • isDaemon(): This method returns true if the thread is a daemon thread, which means it runs in the background and does not prevent the JVM from exiting even if it's still running.
  • isAlive(): This method returns true if the thread is still alive (i.e., not terminated).
  • isInterrupted(): This method returns true if the thread has been interrupted (i.e., if its interrupted status flag is set).

Source Code

public class CurrentThreadInfo
{
	public static void main(String[] args)
	{
		// Get the current executing thread
		Thread currentThread = Thread.currentThread();
 
		// Print thread information
		System.out.println("Thread Name : " + currentThread.getName());
		System.out.println("Thread ID : " + currentThread.getId());
		System.out.println("Thread Priority : " + currentThread.getPriority());
		System.out.println("Thread State : " + currentThread.getState());
		System.out.println("Thread is Daemon : " + currentThread.isDaemon());
		System.out.println("Thread is Alive : " + currentThread.isAlive());
		System.out.println("Thread is Interrupted : " + currentThread.isInterrupted());
	}
}

Output

Thread Name : main
Thread ID : 1
Thread Priority : 5
Thread State : RUNNABLE
Thread is Daemon : false
Thread is Alive : true
Thread is Interrupted : false