Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Tuesday, November 3, 2015

The States of a Thread in Java


three thread states—new, runnable and terminated

A program can access the state of the thread using Thread.State enumeration. The Thread class has the getState() instance method, which returns the current state of the thread.

BasicThreadStates.java
package com.appfworks.threads;

/**
* Created by suresh on 03/11/15.
*/
class BasicThreadStates extends Thread {
public static void main(String []s) throws Exception {
Thread t = new Thread(new BasicThreadStates());
System.out.println("Just after creating thread; \n" +
" The thread state is: " + t.getState());
t.start();
System.out.println("Just after calling t.start(); \n" +
" The thread state is: " + t.getState());
t.join();
System.out.println("Just after main calling t.join(); \n" +
" The thread state is: " + t.getState());
}
}

Just after the creation of the thread and just before calling the start() method on that thread, the thread is in the new state.

After calling the start() method, the thread is ready to run or is in the running state , so it is in runnable state.

t.join() successfully gets executed by the main() thread, it means that the thread t has died or terminated. So, the thread is in the terminated state now.

Two States in “Runnable” State


Once a thread makes the state transition from the new state to the runnable state, you can think of the thread having two states at the OS level: the ready state and running state. A thread is in the ready state when it is waiting for the OS to run it in the processor. When the OS actually runs it in the processor, it is in the running state.

No comments:

Post a Comment