In Java, you can determine the state of a thread by using its Thread.State enumeration. The Thread.State enum represents the various states a thread can be in during its lifetime.
Thread.State enum syntax in java.lang package
public enum Thread.State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
Code language: PHP (php)
Here are the different thread states:
NEW: The thread has been created but has not yet started executing. It is in this state when the Thread object is created, but the start() method has not been called.
RUNNABLE: The thread is currently executing in the JVM. However, it may be executing code in the Java application or be in a waiting state due to synchronization.
BLOCKED: The thread is blocked waiting for a monitor lock. This happens when the thread tries to enter a synchronized block or method but another thread already holds the lock.
WAITING: The thread is in a waiting state and will remain so until another thread explicitly wakes it up using the notify(), notifyAll(), or join() methods.
TIMED_WAITING: Similar to the WAITING state, but the thread will wait for a specified period of time or until a certain condition is met.
TERMINATED: The thread has completed its execution and has terminated.
Program Implementation
//ThreadStateDemo.java class MyThread extends Thread { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadStateDemo{ public static void main(String[] args) { MyThread myThread = new MyThread(); // Get the initial state of the thread System.out.println("Initial state: " + myThread.getState()); myThread.start(); // Give some time for the thread to start and execute try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // Get the state of the thread after it has started System.out.println("State after start(): " + myThread.getState()); // Wait for the thread to complete its execution try { myThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Get the state of the thread after it has terminated System.out.println("State after termination: " + myThread.getState()); } } /* D:\javac ThreadStateDemo.java D:\>java ThreadStateDemo Initial state: NEW State after start(): TIMED_WAITING State after termination: TERMINATED */