Thread Life Cycle in Java
In Java, a thread goes through various stages in its life cycle. These stages define the different states a thread can be in at any given time. The life cycle of a thread consists of the following five states:
1. New (Created) State
-
When a thread object is created using the
Thread
class but has not yet started, it is in the New state. -
It remains in this state until the
start()
method is called.
Example:
2. Runnable State
-
When the
start()
method is called, the thread moves from the New state to the Runnable state. -
The thread is ready for execution but is waiting for CPU time to be assigned by the scheduler.
Example:
3. Running State
-
When the thread scheduler assigns CPU time, the thread enters the Running state and starts execution.
-
This is where the
run()
method executes.
Example:
4. Blocked/Waiting State (Suspended State)
-
A thread moves to a blocked or waiting state if it needs to wait for another thread to release resources or a signal.
-
A thread can enter this state using:
-
wait()
: The thread waits indefinitely until notified. -
sleep(time)
: The thread sleeps for a specific time. -
join()
: The thread waits for another thread to complete.
-
Example:
5. Terminated (Dead) State
-
When the
run()
method finishes execution or if the thread is stopped forcefully, it moves to the Terminated state. -
A terminated thread cannot be restarted.
Example:
Thread Life Cycle Diagram:
Program :
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is in RUNNING state.");
try {
Thread.sleep(2000); // Moves to TIMED_WAITING state
System.out.println(Thread.currentThread().getName() + " is back to RUNNING state.");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has completed execution (TERMINATED).");
}
}
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Thread is in NEW state
System.out.println("Thread state after creation: " + t1.getState());
t1.start(); // Moves to RUNNABLE state
System.out.println("Thread state after calling start(): " + t1.getState());
try {
Thread.sleep(500); // Ensures main thread waits for some time
System.out.println("Thread state while it is sleeping: " + t1.getState());
t1.join(); // Ensures main thread waits for t1 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread state after completion: " + t1.getState());
}
}
Output:
No comments:
Post a Comment