Thread life cycle in java
In Java, the life cycle of a thread refers to the stages a thread goes through from its creation to its termination. The Java thread life cycle is represented by the following states:
- New: The thread is in this state when an instance of the
Thread
class is created but before thestart()
method is called. - Runnable: The thread is in this state after calling the
start()
method. It is ready to run, but the scheduler has not selected it to be the running thread yet. - Blocked: The thread is in this state when it is waiting for a monitor lock to enter a synchronized block/method or waiting for I/O operations to complete.
- Waiting: The thread is in this state when it is waiting indefinitely for another thread to perform a particular action.
- Timed Waiting: The thread is in this state when it is waiting for another thread to perform a particular action, but with a specified waiting time.
- Terminated: The thread is in this state when its
run()
method completes or when thestop()
method is called.
Here’s an example that illustrates the Java thread life cycle:
Example
/*
* Author: Zameer Ali Mohil
* */
public class ThreadLifecycleExample {
public static void main(String[] args) {
// New State
Thread myThread = new Thread(() -> {
// Runnable State
System.out.println("Thread is running...");
try {
// Timed Waiting State
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread has completed.");
});
// Runnable State (after start() is called)
myThread.start();
try {
// Main thread sleeps for a while
Thread.sleep(1000);
// Blocked State (waiting for myThread to complete)
myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Terminated State
System.out.println("Main thread exiting.");
}
}
In this example:
- The
myThread
is in the New State after its creation. - After calling
start()
, it enters the Runnable State and becomes eligible for execution. - Inside the
run()
method, it is in the Runnable State as it is actively executing. - The
sleep(2000)
call puts it into the Timed Waiting State for 2 seconds. - The main thread (
main()
method) sleeps for a while, putting the main thread into the Timed Waiting State. - The
join()
method is called, putting the main thread into the Blocked State untilmyThread
completes. - After
myThread
completes, it enters the Terminated State.
When you run this program, you’ll see output indicating the different states the threads are in during their life cycle. Keep in mind that the exact order of states might vary due to the nature of thread scheduling.