Lifecycle and States of a Thread in Java

161

threadstates.png

  1. New -> Runnable
  • A thread is in New state when it is created new Thread() but not yet started. It remains in New and only enters Runnable until the start() method is called. Threads in Runnable 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 other Runnable threads so that other threads can get a chance to run.
  1. 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);
  1. Runnable -> Waiting

    A thread enters Waiting state by calling one of the following methods:

  • Object.wait();
  • Thread.join();
  • LockSupport.park();
  1. 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.
  1. Timed Waiting -> Runnable

    A thread will move from Timed Waiting to Runnable when:

  • calling LockSupport.unpark();.
  • join() execution ends.
  • wait() and sleep() time is up.
  1. / 8. Timed Waiting -> Blocked / Waiting -> Blocked
  • When a thread in the wating state is awakened by calling notify()/notifyAll(), it will enter the Blocked state. It can enters Runnable state only when it acquires the monitor given up by the the calling thread that wakes it up.
  1. Waiting -> Runnable

    A thread will move from Waiting to Runnable when:

  • calling LockSupport.unpark()
  • join() execution ends.
  1. Blocked -> Runnable
  • Once the thread acquires the monitor(lock) , the thread will move its state from blocked to Runnable.
  1. 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.