Friday, 26 August 2016

Thread Scheduler states and Transitions

Thread Scheduler – States and Transitions

This article is in continuation of my previous article : Multithreading Introduction

Thread Scheduler:
It will decide which thread should run at any given moment and also takes out of the run state.
Any thread which is in runnable state can be chosen by the scheduler to be the only running thread and if a thread is not in runnable state it won’t be chosen to be the currently running thread.
However we have a runnable pool ,that when a thread has finished with its turn ,it moves to the end of line of runnable pool and wait util for its turn ,But still the order in which runnable threads are chosen is not guaranteed.
Methods that can influence thread scheduling:
Thread Class methods:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int newPriority)
Object Class Methods :
Public final void wait()
Public final void notify()
Public final void notifyAll()

Thread states :
Since we know that it is the thread scheduler which move the threads from the running state back to runnable state, but there are other factors also which can change the state and can move  a thread from running state
For e.g :- run() once its completes , it will move thread from running to dead state
A thread can be only in one of the five states:

                                               New
                                                   |
                                             Runnable \
                                                |          Waiting/Blocking/sleeping
                                             Running /   
                                                      |
                                                Dead
                                               
                                                
1)  New State : Thread object has been created but start()       method has been not invoked yet, Any new thread begins its life cycle in the New state.
2)  Runnable : In this state thread is eligible to run ,But the schedule has not selected it to be the running thread , A thread first enters the runnable state which start() method is invoked, but it can also remain in runnable state after either running for coming back from a blocked , waiting or sleeping state.
3)  Running : The only way to get into the running state is that the scheduler chooses a thread from the running pool and start executing it.
4)  Waiting/blocking/Sleeping : These is a state where thread is not eligible to run in order words we can say that it is not runnable but return to a runnable state later.

5)  Dead– A thread is considered to be dead once its run method is completed

No comments:

Post a Comment