Java Thread Lifecycle
A Java thread has its own life cycle and it can be only in one of five states:
- Waiting or Sleeping
A thread will be in this state when
Thread instance has been created, but the start() method has not been invoked on the thread.
In this state thread is considered not alive.
A thread enters the runnable state when the
start() method is invoked. When the thread is in the runnable state, it is considered alive. A thread can return back to this state from running, waiting or sleeping state.
This is the state a thread is in when the thread scheduler selects it to be the currently executing process. A thread scheduler select a thread from the runnable pool.
Waiting or Sleeping
A thread is in this state when the thread is still alive, but is currently not eligible to run. A thread is in blocked state when it is waiting for a resource for example like I/O or an object's lock. Once those resources are available, thread is again available to be back in running state.
A thread is in sleeping state when a Java code call it to sleep some time and once that time is expired the thread is available to jump back to running state.
sleep() method is used to push the thread to sleeping state.
A thread is terminated when its
run() method completes. Once a thread is dead, it can never be brought back to life. If you invoke
start() on a dead Thread instance, you'll get a runtime exception.