Lifecycle and States of a Thread in Java
New
->Runnable
- A thread is in
New
state when it is creatednew Thread()
but not yet started. It remains inNew
and only entersRunnable
until thestart()
method is called. Threads inRunnable
state are either running or ready to run at any instant of time, but they’re waiting for resource allocation from the CPU. In a multi-threaded environment, the Thread-Scheduler (which is part of JVM) allocates a fixed amount of time to each thread, each and every thread runs for a particular amount of time, then pauses and relinquishes the control to otherRunnable
threads so that other threads can get a chance to run.
-
Runnable
->Timed Waiting
A thread enters
Timed Waiting
state by calling one of the following methods with a specified positive waiting time:
- Object.wait(long timeout);
- Thread.sleep(long millis);
- Thread.join(long millis);
- LockSupport.parkUntil(long deadline);
- LockSupport.parkNanos(long nanos);
-
Runnable
->Waiting
A thread enters
Waiting
state by calling one of the following methods:
- Object.wait();
- Thread.join();
- LockSupport.park();
Runnable
->Blocked
- When a thread enters a synchronized block, if the thread does not hold the monitor(lock) associated with the object that the block is synchronized on, the thread will be in
blocked
state waitng for the monitor until it acquires the monitor released by other threads.
-
Timed Waiting
->Runnable
A thread will move from
Timed Waiting
toRunnable
when:
- calling
LockSupport.unpark();
. join()
execution ends.wait()
andsleep()
time is up.
- / 8.
Timed Waiting
->Blocked
/Waiting
->Blocked
- When a thread in the wating state is awakened by calling
notify()/notifyAll()
, it will enter theBlocked
state. It can entersRunnable
state only when it acquires the monitor given up by the the calling thread that wakes it up.
-
Waiting
->Runnable
A thread will move from
Waiting
toRunnable
when:
- calling
LockSupport.unpark()
join()
execution ends.
Blocked
->Runnable
- Once the thread acquires the monitor(lock) , the thread will move its state from
blocked
toRunnable
.
-
Runnable
->Terminated
A thread terminates because of either of the following reasons:
-
terminated normally when the
run()
method has been entirely executed -
terminated abnormally when an unhandled exception is thrown.