Thread StatesIn java, Thread has different states in system. Thread can run, sleep, pause and wait for it’s execution. We will discuss different states or life cycle of a thread in java. We will also discuss about Thread Scheduler and what is the purpose of it.
Thread scheduler is actually the part of Java Virtual Machine that decides which thread should run at any given moment. It’s thread scheduler’s responsibility to set the priority of number of threads in the queue waiting for their turn to execute.
Let’s assume, you only have single processor system but your application require multiple resource through the threads so it’s thread scheduler that will decide which thread is eligible to run first and which should wait for it’s turn.
Remember one thing, the order in which threads run may vary platform to platform. Thread scheduler can choose any thread to run.
Thread scheduler manages the states of a Thread. It can run a thread, can move running thread to runnable state. So let’s discuss different states a thread manages during it’s life cycle in java.
New : This is the state when we create an instance of thread class but start() method has not been invoked yet. In this state, a thread is considered not alive.
Runnable : This is the state when thread is eligible to run. Thread scheduler has not selected this thread to be running thread. Before a thread can run, it first enters into the runnable state when start() method is invoked. A thread can also return into runnable state after running, blocked, waiting or sleep. A thread is now alive.
Running : Thread scheduler creates a separate pool which is called runnable pool where number of threads are waiting to be selected as running thread. This is the time when Thread scheduler selects a thread from runnable pool to be currently executing process. In this state, a particular thread perform it’s operation for which it is made of.
Waiting or Blocked or Sleeping : These three states are combined together because they all have one thing in common. They all are alive but they are not eligible to run yet. A particular thread may be block due to unavailability of the resource which is required for this thread to complete it’s execution.
A thread may be in waiting state because resource is taking some time to respond, in that case thread will wait for the period of time.
A thread may be in sleeping state because of the code we wrote. It is required for this thread to sleep for the some time.
Dead : A thread is considered dead if it’s run method completes it’s execution. Thread is no longer available now. Once thread in dead state, it can never be brought back to life.