Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Thread Lifecycle in Java? Explain all thread states. Java में Thread Lifecycle क्या है? सभी states explain करें।

Answer

Thread lifecycle consists of five states: New, Runnable, Running, Blocked/Waiting, and Terminated. Understanding state transitions is crucial for multithreading.

StateDescriptionTransition
NewThread created but not startedstart() called
RunnableReady to run, waiting for CPUScheduler selects
RunningCurrently executingContext switch
Blocked/WaitingWaiting for resource/eventResource available
TerminatedFinished executionEnd of run()
public class ThreadLifecycleDemo {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println('Thread is running');
            try {
                Thread.sleep(2000);  // Waiting state
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println('Thread finished');
        });
        
        System.out.println('State: ' + t.getState());  // NEW
        
        t.start();
        System.out.println('State: ' + t.getState());  // RUNNABLE
        
        try {
            t.join();  // Wait for thread to finish
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println('State: ' + t.getState());  // TERMINATED
    }
}

// Thread state transitions:
// New -> Runnable: start() called
// Runnable -> Running: Scheduler selects
// Running -> Runnable: Context switch
// Running -> Waiting: sleep(), wait(), join()
// Waiting -> Runnable: notify(), time expires
// Running -> Terminated: run() ends

// Thread.State enum values:
// NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
Thread States:

1. NEW: Thread create हुआ, start() नहीं हुआ
2. RUNNABLE: CPU के लिए ready
3. RUNNING: Actively executing
4. BLOCKED/WAITING: Resource के लिए wait
5. TERMINATED: Complete हो गया

State Transitions:
NEW -> start() -> RUNNABLE
RUNNABLE -> Scheduler -> RUNNING
RUNNING -> sleep()/wait() -> WAITING
WAITING -> notify()/time -> RUNNABLE
RUNNING -> end() -> TERMINATED

Was this answer clear?