Video in progress
What states does a thread go through, and where can you see them?
Thread.State has six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. You see them through getState() or in a thread dump (jstack).
📖 Answer
- NEW: the object has been created, but
start()hasn't been called yet. - RUNNABLE: running, or waiting for its turn on the CPU. Note that a thread reading from a socket often shows up as RUNNABLE too.
- BLOCKED: it wants to enter a
synchronizedblock, but another thread holds the monitor. - WAITING: waiting indefinitely:
wait(),join(),LockSupport.park(). - TIMED_WAITING: waiting with a timeout:
sleep(1000),wait(500),poll(1, SECONDS). - TERMINATED:
run()finished or exited with an exception.
Thread t = new Thread(() -> sleepQuietly(5000));
System.out.println(t.getState()); // NEW
t.start();
Thread.sleep(100);
System.out.println(t.getState()); // TIMED_WAITING
In practice you need these states when reading a thread dump. If many threads are BLOCKED, there is a pile-up on some lock. If all the threads in a pool are WAITING, they are just sitting there waiting for work, and that is normal.
Sign up to mark studied questions and save your progress.