Java-Obtaining Thread State

Obtaining Thread State

Every thread moves through several states from its creation to its termination. The possible states of a thread are: NEW, RUNNABLE, WAITING, BLOCKED and TERMINATED. Immediately after the creation of a thread, it will be in the NEW state. After the start( ) method of the Thread class is executed, it will move to the RUNNABLE state. When the thread completes its execution, it will move to the TERMINATED stage.

If a thread is instructed to wait, it moves to the WAITING state. When the waiting is over, the thread once again moves to the RUNNABLE state. You can obtain the current state of a thread by calling the getState( ) method defined by Thread. It returns a value of type Thread.State that indicates the state of the thread at the time at which the call was made. State is an enumeration defined by Thread. Given a Thread instance, you can use getState( ) to obtain the state of a thread.

Program

final


Program Source

class NewThread extends Thread {
    
    public void run()
    {
        for(int i=10;i<=50;i+=10)
        {
            System.out.println(getName()+" : "+i);
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        NewThread th1 = new NewThread();
        System.out.println("Thread th1 State : "+th1.getState());
        th1.start();
        System.out.println("Thread th1 State : "+th1.getState());
        try {
            th1.join();
        }catch(InterruptedException ie)
        {
            System.out.println("Main Thread Interrupted");
        }
        System.out.println("Thread th1 State : "+th1.getState());
    }
}

Leave a Comment