I’m looking for verification/arguments on the following:
A thread is in exactly one of the 5 (+1 — 2 for WAITING
) states at any point of time.
Suppose a thread T
calls
Thread.sleep(3000);
and thus puts itself into sleep for 3 secs.
Which state is it in during those 3 secs?
It’s clearly start()
-ed and is still alive, thus is neither NEW
nor TERMINATED
.
It isn’t waiting on any lock. in fact, it hasn’t released any of the locks it had just before this call, so it isn’t BLOCKED
.
It’s not waiting on another thread. Is waiting on itself in some sense– but that’s not the specification of the WAITING
state. What gets a thread into a WAITING
state is one of the calls: Object.wait()
, Thread.join()
and LockSupport.park()
.
So it should be RUNNABLE
— the only one left out among the thread states.
However, RUNNABLE
is the state a thread is executing on JVM– is enabled for CPU time and thus for burning resources.
A sleeping thread being on CPU schedule seems contradictory.
Am i missing anything here?
TIA.
Advertisement
Answer
The Javadoc of Thead.State.TIMED_WAITING reads:
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:
Thread.sleep
Object.wait
with timeoutThread.join
with timeoutLockSupport.parkNanos
LockSupport.parkUntil
And indeed, the following test program prints TIMED_WAITING:
public class Test { public static void main(String[] args) throws Exception { Thread t = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }; }; t.start(); Thread.sleep(100); // make sure the other thread has started System.out.println(t.getState()); } }