Java Intermediate

0% completed

Previous
Next
Lifecycle and States of a Thread in Java

In Java, every thread goes through a lifecycle with distinct states from its creation until its termination. Understanding these states is essential for developing robust multithreaded applications and for debugging threading issues. A thread's state reflects what it is currently doing, and the Java Virtual Machine (JVM) manages transitions between these states during execution.

Thread States

The following table summarizes the main states of a thread along with their descriptions:

StateDescription
NewThe thread has been created but has not yet started execution.
RunnableThe thread is ready to run and is waiting for CPU time. This includes threads that are actually running.
BlockedThe thread is blocked waiting for a monitor lock (e.g., waiting to enter a synchronized block).
WaitingThe thread is waiting indefinitely for another thread to perform a specific action (e.g., via wait()).
Timed WaitingThe thread is waiting for another thread to perform an action for a specified period (e.g., via sleep() or join(timeout)).
TerminatedThe thread has completed its execution or has been terminated.
Image

Examples

Example 1: Observing Thread States

This example demonstrates how to observe the lifecycle of a thread by printing its state at different stages using the getState() method.

Java
Java

. . . .

Example Explanation:

  • Initial State (NEW):
    • Before calling start(), the thread is created but not yet scheduled.
  • After start() (RUNNABLE):
    • The thread becomes eligible to run, entering the RUNNABLE state.
  • During Sleep (TIMED_WAITING):
    • Inside run(), Thread.sleep(2000) causes the thread to enter TIMED_WAITING (this may not be visible if printed at an exact moment).
  • After Completion (TERMINATED):
    • Once run() finishes, the thread enters the TERMINATED state.

Understanding the lifecycle and states of a thread is crucial for effective multithreading in Java. Threads transition through various states such as New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated during their execution. By using methods like start(), sleep(), and join(), you can manage thread execution and synchronize operations. The provided examples illustrate how to observe these state transitions and how to use join() to coordinate thread completion.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next