Sobes.tech
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:

  1. NEW: The thread has been created but start() has not been called yet.
  2. RUNNABLE: The thread is ready to run and waiting for CPU time.
  3. BLOCKED: The thread is waiting to acquire a monitor lock to enter a synchronized block or method.
  4. WAITING: The thread is waiting indefinitely for another thread to perform a particular action (e.g., wait() without timeout).
  5. TIMED_WAITING: The thread is waiting for a specified amount of time (e.g., sleep(), wait(timeout), join(timeout)).
  6. 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.

Can you list the possible thread states in Java and… - sobes.tech