Junior — Middle
Can you list the possible thread states in Java and explain them?
sobes.tech AI
Answer from AI
In Java, a thread can be in the following states:
- NEW: The thread has been created but
start()has not been called yet. - RUNNABLE: The thread is ready to run and waiting for CPU time.
- BLOCKED: The thread is waiting to acquire a monitor lock to enter a synchronized block or method.
- WAITING: The thread is waiting indefinitely for another thread to perform a particular action (e.g.,
wait()without timeout). - TIMED_WAITING: The thread is waiting for a specified amount of time (e.g.,
sleep(),wait(timeout),join(timeout)). - TERMINATED: The thread has finished execution.
Example transitions:
Thread t = new Thread(() -> {
// thread code
});
// State is NEW
t.start();
// Transition to RUNNABLE
// If the thread tries to enter a synchronized block but it's occupied, it transitions to BLOCKED
// Calling wait() puts the thread into WAITING
// Calling sleep(1000) puts the thread into TIMED_WAITING
// After run() completes, the thread transitions to TERMINATED
Understanding these states is important for proper thread management and avoiding synchronization and performance issues.