Member-only story
What Are the Different Thread States in Java with Code Examples? — IT Interview Guide
What Are the Different Thread States in Java with Code Examples?
In Java, thread management is a critical concept for building efficient, high-performance applications. The java.lang.Thread
class provides built-in support for multithreading, and understanding the Thread lifecycle is essential to effectively utilize these capabilities.
Java threads can exist in the following states as defined in the Thread.State
enum:
Let’s explore each state with detailed explanations and code examples to bring the concept to life.
1. NEW
A thread is in the NEW state when it is created but not yet started.
Thread t = new Thread(() -> {
System.out.println("Running thread");
});
System.out.println(t.getState()); // Output: NEW
Explanation: The thread object is instantiated, but start()
has not been invoked.
2. RUNNABLE
A thread is in the RUNNABLE state after the start()
method is called and before it enters the waiting or terminated states.
Thread t = new Thread(() -> {
while(true) {
// Simulating work
}
});
t.start()…