A thread has various states during its lifetime. It is important to understand the different states of a thread and learn to write robust code based on that understanding. You will see three thread states: 1) new, 2) runnable and 3) terminated,
which are applicable to almost all threads you will create in this section.
BasicThreadStates.java
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());
}
}
This program prints the following: Just after creating thread;
The thread state is: NEW Just after calling t.start();
The thread state is: RUNNABLE Just after main calling t.join();
The thread state is: TERMINATED
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. There might be many threads waiting for processor time.
The current thread may end up taking lots of time and finally may give up the CPU voluntarily. In that case, the thread again goes back to the ready state.