In Java, a Thread goes through multiple states from creation to termination. This journey is called the Thread Life Cycle. Understanding this life cycle is essential for writing efficient multithreaded applications.
start(), sleep(), and join()A thread in Java passes through the following main states:
// Demonstrates basic thread life cycle
class MyThread extends Thread {
public void run() {
// Code inside run() represents the Running state
System.out.println("Thread is running");
}
}
public class ThreadLifeCycle {
public static void main(String[] args) {
// Thread is in New state
MyThread t = new MyThread();
// Thread enters Runnable state
t.start();
}
}
Thread is running
Explanation: The thread is first created (New), then started using start(), after which the JVM calls the run() method and the thread enters the Running state.
start() instead of calling run() directlysleep() to observe the Waiting state