This section explains how to get state of a thread in java Thread.
This section explains how to get state of a thread in java Thread.This section explains how to get state of a thread in java Thread.
Thread getState() :
Suppose you want to know the state of the thread so for that Java Thread provides Thread.getState() method to get the state of the thread.
public Thread.State getState() : This method
returns the state of the specified thread. its function to monitor the
system state but do not for synchronization control.
Example : This example display the different states of the thread.
class ThreadGetState implements Runnable { Thread thread; @Override public void run() { Thread.State state = thread.currentThread().getState(); System.out.println(thread.currentThread().getName() + " state is - " + state); } public static void main(String[] args) { Thread th = new Thread(new ThreadGetState()); Thread th1 = new Thread(new ThreadGetState()); th.start(); try { th.sleep(1000); } catch (Exception e) { System.out.println(e); } Thread.State state = th.getState(); System.out.println(th.getName() + " state is - " + state); System.out.println(th1.getName() + " state is - " + th1.getState()); th1.start(); try { th1.join(); } catch (Exception e) { System.out.println(e); } System.out.println(th1.getName() + " state is - " + th1.getState()); } }
Output :
Thread-0 state is - RUNNABLE Thread-0 state is - TERMINATED Thread-1 state is - NEW Thread-1 state is - RUNNABLE Thread-1 state is - TERMINATED