Understanding the Thread Lifecycle in Java: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-09-28 07:42:12   7667  Share
Subject Syllabus DetailsSubject Details 3 Questions
☰ TContent
☰Fullscreen

Table of Content:

When a thread is created, a new thread of control is added to the current process. Every process has at least one thread of control, in the program's main() routine. Each thread in the process runs simultaneously and has access to the calling process's global data. In addition, each thread has its own private attributes and call stack.

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

Thread having below states.

  1. New State
  2. Ready State
  3. Running State
  4. Dead State
  5. Non-Runnable States (Blocked)
life cycle of thread in java

1.New State:

A thread has been created but not started yet. A thread will be started by calling its start() method.

2.Runnable State:

This state is also called ready to run stage also called queue. A thread starts in the runnable state by calling start() method.

The Thread scheduler decides which thread runs and how long.

3.Running State:

If a Thread is executing that means Thread is in Running stage.

4.Dead State:

Once a Thread reached dead state it can not run again.

5. Non-runnable States:

This is the state when the thread is still alive, but is currently not eligible to run.

  • A Running Thread transit to one of the non-runnable states, depending upon the circumstances.
  • A Thread remains non-runnable until a special transition occurs.
  • A Thread does not go directly to the running state from non-runnable state.
  • But transits first to runnable state.
  1. Sleeping: The Thread sleeps for the specified amount of time.
  2. Blocked for I/O: The Thread waits for a blocking operation to complete.
  3. Blocked for join completion: The Thread waits for completion of another Thread.
  4. Waiting for notification: The Thread waits for notification another Thread.
  5. Blocked for lock acquisition: The Thread waits to acquire the lock of an object.
  • JVM executes the Thread based on their priority and scheduling.