Thread Lifecycle in Java
#Thread Lifecycle in Java
Introduction
In Java multithreading, a thread does not remain in a single state throughout its lifetime. Instead, it goes through a well-defined lifecycle managed by the Java Virtual Machine (JVM). Understanding the thread lifecycle is essential for writing efficient and bug-free multithreaded applications.
A thread in Java can be in one of the following states as defined by the Thread.State
enum:
New
A thread that is created but not yet started using start()
.
Example: Thread t = new Thread();
Runnable
The thread is ready to run but waiting for CPU scheduling.
Example: After calling t.start()
, the thread enters the Runnable state.
Running
The thread is actively executing its run()
method.
Only one thread per CPU core can be in this state at a time.
Waiting
The thread waits indefinitely for another thread to signal.
Example: Using wait()
without a timeout.
Timed Waiting
The thread waits for a specific period of time.
Example: sleep(milliseconds)
, join(milliseconds)
.
Terminated (Dead)
The thread has finished execution and cannot be restarted.
New → Runnable → Running → Waiting/Timed Waiting → Terminated
class ThreadLifecycleDemo extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running...");
try {
Thread.sleep(1000); // Timed Waiting
synchronized(this) {
wait(); // Waiting
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
ThreadLifecycleDemo t1 = new ThreadLifecycleDemo();
System.out.println("State after creation: " + t1.getState()); // NEW
t1.start();
System.out.println("State after start: " + t1.getState()); // RUNNABLE
Thread.sleep(200);
System.out.println("State while running: " + t1.getState());
Thread.sleep(1500);
System.out.println("State after sleep: " + t1.getState()); // WAITING
}
}
A thread in Terminated state cannot be restarted.
Runnable does not mean the thread is running, only that it is eligible to run.
Synchronization methods like wait()
, notify()
, and join()
affect the lifecycle.
Understanding the thread lifecycle in Java is crucial for building efficient multithreaded applications. Proper management of thread states helps avoid issues like deadlocks, race conditions, and thread starvation.
SEO Keywords to Target:
Thread lifecycle in Java
Java thread states
Java multithreading lifecycle
Thread lifecycle diagram in Java
Java concurrency and threading