Java Thread Life Cycle
In Java, a thread goes through several states during its lifetime. These states represent the life cycle of a thread.
Java में, एक थ्रेड अपने जीवनकाल में कई अवस्थाओं से गुजरता है। ये अवस्थाएँ थ्रेड के जीवन चक्र को दर्शाती हैं।
Thread Life Cycle States
- New: Thread object is created.
- Runnable: Thread is ready to run but waiting for CPU.
- Running: Thread is currently executing.
- Waiting: Thread is waiting indefinitely for another thread.
- Timed Waiting: Thread is waiting for a specific period.
- Terminated (Dead): Thread has finished execution.
- New: थ्रेड ऑब्जेक्ट बनाया गया है।
- Runnable: थ्रेड रन के लिए तैयार है पर CPU का इंतज़ार कर रहा है।
- Running: थ्रेड वर्तमान में रन कर रहा है।
- Waiting: थ्रेड अनिश्चित समय के लिए किसी और थ्रेड का इंतज़ार कर रहा है।
- Timed Waiting: थ्रेड एक तय समय के लिए इंतज़ार कर रहा है।
- Terminated (Dead): थ्रेड का execution खत्म हो गया है।
Example: Simple Thread Life Cycle
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Thread finished.");
}
public static void main(String[] args) {
MyThread t = new MyThread();
System.out.println("Thread State: " + t.getState()); // NEW
t.start();
System.out.println("Thread State after start(): " + t.getState()); // RUNNABLE
try {
t.join();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Thread State after finish: " + t.getState()); // TERMINATED
}
}
Thread State: NEW
Thread State after start(): RUNNABLE
Thread is running...
Thread finished.
Thread State after finish: TERMINATED
Thread State after start(): RUNNABLE
Thread is running...
Thread finished.
Thread State after finish: TERMINATED
This program shows how a thread moves from NEW → RUNNABLE → RUNNING → TERMINATED state.
यह प्रोग्राम दिखाता है कि थ्रेड NEW → RUNNABLE → RUNNING → TERMINATED स्थिति में कैसे जाता है।