Monday, 3 March 2014

Thread States, Transitions and Scheduler

Thread States and Transitions


Thread has the following five states.

  1. New

  2. Runnable

  3. Running

  4. Waiting/blocking/sleeping

  5. Dead


New – This is the state where the thread is created either by extending the thread class or by implementing the runnable interface. But the start method is not called on the thread. At this stage is thread is not live.
Runnable – When start method is called on a thread, it comes to runnable state and it is called as alive at this stage. But still the actual thread of execution is not started until the thread scheduler selects it. Thread also comes to runnable state after coming back from blocked, waiting or sleeping state.
Running – This is the state where the threads are selected from the runnable pool. At this time, threads are in execution. Threads may go to runnable from this state, when it enter inside blocked, waiting or sleeping.

[caption id="attachment_481" align="aligncenter" width="770"]Thread states and transitions Thread states and transitions[/caption]

Waiting/blocking/sleeping: Thread is alive but not eligible to run. Once the event occurs, it goes to runnable and again it waits for the thread scheduler to select.
Dead: A thread is set to be dead when it completes the run method. It is still a thread object, but not anymore the thread of execution

Thread Scheduler:
The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming In a single processor single core machine there will be only one thread running all the time. So the thread scheduler decides which thread to run.Any thread in runnable pool can be selected by thread scheduler for run. The order of selecting the runnable thread are not guaranteed. It is the scheduler which decides on this. That’s why it is called runnable pool rather than runnable queue.

Influencing thread scheduler
There is no way to control the thread scheduler but there are ways to influences. Thread provides some method for that,
Methods from the java.lang.Thread Class

  • public static void sleep(long millis) throws InterruptedException -

  • public static void yield()

  • public final void join() throws InterruptedException

  • public final void setPriority(int newPriority)


Methods from the java.lang.Object Class

  • public final void wait() throws InterruptedException

  • public final void notify()

  • public final void notifyAll()

No comments:

Post a Comment