Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 201 ยท Concurrency

Thread Lifecycle and Priorities

Learn the Java thread lifecycle - NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED with getState demos, thread priorities and how to interrupt threads.

A thread isn't simply "running" or "not running". Between being created and finishing, it can be waiting for a lock, sleeping, or waiting for another thread to do something. Java names these situations precisely in the Thread.State enum, and getState() tells you which one a thread is in right now. Knowing the states is how you read a thread dump when a server hangs, and how you understand what sleep, join and synchronized actually do.

This lesson walks through all six states with live demos, explains thread priorities (and why they rarely help), and then covers the most important skill in this chapter: interrupting a thread to ask it to stop, and handling InterruptedException correctly. It builds on Threads.

The six thread states

State Meaning Typical cause
NEW created, start() not called yet new Thread(...)
RUNNABLE running, or ready to run when the CPU is free executing code, or blocked in some I/O calls
BLOCKED waiting to enter a synchronized block held by another thread lock contention
WAITING waiting with no time limit for another thread to act join(), wait(), LockSupport.park()
TIMED_WAITING the same, but with a time limit sleep(ms), join(ms), wait(ms)
TERMINATED run() has finished, normally or with an exception

A thread moves through them like this:

TEXT
NEW โ”€โ”€ start() โ”€โ”€โ–บ RUNNABLE โ”€โ”€ run() ends โ”€โ”€โ–บ TERMINATED
                     โ–ฒ   โ”‚
                     โ”‚   โ”œโ”€ needs a synchronized lock held by another thread โ”€โ”€โ–บ BLOCKED
                     โ”‚   โ”œโ”€ wait(), join(), LockSupport.park() โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ WAITING
                     โ”‚   โ””โ”€ sleep(ms), wait(ms), join(ms) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ TIMED_WAITING
                     โ”‚
                     โ””โ”€โ”€ back to RUNNABLE when: the lock is acquired, the thread is
                         notified, the joined thread ends, the time runs out, or it is interrupted

Two points surprise people. First, Java has no separate "running" state: RUNNABLE covers both "on a CPU right now" and "ready, waiting for the scheduler". Second, a thread stuck reading from a socket or file is usually reported as RUNNABLE, because the JVM sees it executing native code, even though it isn't using any CPU.

Watching the states

This program puts threads into each state and prints what getState() reports. The awaitState helper polls until the thread reaches the expected state (with a time limit), because a freshly started thread needs a moment to get there.

Java All six thread states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step by step:

  • Before start(), the sleeper is NEW. While running, it sees itself as RUNNABLE (a thread asking about itself is always running).
  • Inside sleep(400), it's TIMED_WAITING.
  • The joiner calls sleeper.join() without a timeout, so it's WAITING until the sleeper ends.
  • main holds lock while the third thread tries to enter synchronized (lock), so that thread is BLOCKED. As soon as main leaves its block, the thread gets the lock and continues.
  • After run() returns, a thread is TERMINATED forever; it can't be restarted.

getState() is a snapshot that may already be out of date when you read it. It's great for monitoring and debugging, but never use it to coordinate threads; that's what join, locks and the tools in later lessons are for. To check whether a thread has started and not yet finished, isAlive() is the simpler question.

Thread dumps

On a real server you inspect thread states with a thread dump: a list of every thread with its state and stack trace. Run jcmd <pid> Thread.print or jstack <pid> (both ship with the JDK), or press Ctrl+Break (Windows) / send kill -3 (Linux, macOS) to a running JVM. Many BLOCKED threads point to lock contention; many threads WAITING on the same thing point to a stuck resource; two threads BLOCKED on each other's locks are a deadlock, and the dump says so explicitly.

TEXT
"blocked" #22 prio=5 os_prio=0 tid=0x... nid=0x... waiting for monitor entry
   java.lang.Thread.State: BLOCKED (on object monitor)
        at Main.lambda$main$2(Main.java:31)
        - waiting to lock <0x000000071a8b3c10> (a java.lang.Object)

This is one more reason to name your threads: a dump full of Thread-17 is much harder to read.

Thread priorities

Every thread has a priority from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10); the default is Thread.NORM_PRIORITY (5), and a new thread inherits its creator's priority. You can change it with setPriority:

Java Setting and inheriting priorities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The catch: a priority is only a hint to the operating system's scheduler, and what it does depends on the platform. On Linux the HotSpot JVM ignores Java priorities by default; on Windows they map to OS priorities but are still not strict. A program whose correctness depends on priorities is broken. Use them, if at all, to nudge background work (like a cache cleanup) to the back. Virtual threads always have priority 5 and ignore setPriority.

Interrupting a thread

Java threads stop cooperatively. To ask a thread to stop, you call thread.interrupt(). That does two things:

  1. It sets the thread's interrupt flag (a boolean on the thread).
  2. If the thread is in sleep, wait, join or another interruptible blocking call, that call wakes up immediately and throws InterruptedException, and the flag is cleared.

Nothing else happens. A thread that never checks the flag and never blocks will ignore the interrupt completely. Here is a sleeping thread being interrupted:

Java Interrupting a sleeping thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The 5-second sleep ends at once. Note the output flag after the exception: false: throwing InterruptedException clears the flag. That detail is the source of the most common interrupt bug, coming up in a moment.

Checking the flag in a busy loop

A thread doing CPU work never sleeps, so it must check the flag itself. There are two ways to read it:

  • thread.isInterrupted() reads the flag and leaves it alone. Inside the thread: Thread.currentThread().isInterrupted().
  • The static Thread.interrupted() reads the current thread's flag and clears it. Its name is misleading; use it only when you deliberately want to consume the interrupt.
Java Stopping a busy loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In long loops, check the flag at a natural point, such as once per item processed. Checking very rarely makes cancellation slow; the check itself is cheap.

Handling InterruptedException correctly

InterruptedException is checked, so the compiler forces you to deal with it, and the tempting fix is an empty catch. That swallows the interrupt: the exception cleared the flag, your code ignores it, and the caller that asked the thread to stop never finds out. Look at the difference:

Java Swallowing versus restoring the interrupt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The good worker stops after 2 rounds. The bad one shrugs off the interrupt and runs all 10 rounds; with a while (true) loop it would never stop. The rules:

  1. Best: let it propagate. If your method can declare throws InterruptedException, do that and let the caller decide.
  2. If you can't (for example inside Runnable.run()), restore the flag with Thread.currentThread().interrupt() and return or stop what you're doing.
  3. Never swallow it silently. Only the code that owns the thread (the one that created it) may decide to ignore an interrupt.

Wrapping it, as in throw new RuntimeException(e), is acceptable only if you also restore the flag first.

What interrupts can't do

Interrupts only wake up interruptible operations:

  • sleep, join, Object.wait, BlockingQueue.put/take, Future.get, Lock.lockInterruptibly: throw InterruptedException.
  • Waiting to enter a synchronized block is not interruptible; a BLOCKED thread stays blocked. ReentrantLock.lockInterruptibly() is the interruptible alternative (Locks and Conditions).
  • Classic InputStream.read() on a socket or file is not interruptible. Close the socket from another thread (which makes read throw), set a socket timeout, or use NIO channels, which close when interrupted.

Executors use interrupts too: ExecutorService.shutdownNow() and Future.cancel(true) interrupt the worker threads, which is exactly why your tasks must respond to interrupts (Executors and Thread Pools).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A thread is inside Thread.sleep(1000). What does getState() return for it?

    Sleeping with a duration is a timed wait. WAITING is for waits without a time limit, such as join() or wait(), and BLOCKED is only for waiting to enter a synchronized block.
  2. 2. A thread catches InterruptedException from sleep() and then checks Thread.currentThread().isInterrupted(). What does it get?

    Blocking methods clear the interrupt flag when they throw InterruptedException. That is why code that cannot rethrow must call Thread.currentThread().interrupt() to restore it.
  3. 3. Thread T is waiting to enter synchronized (lock) held by another thread. You call T.interrupt(). What happens?

    Acquiring an intrinsic lock is not interruptible. T keeps waiting, and the flag will be seen later if T checks it. ReentrantLock.lockInterruptibly() offers an interruptible alternative.
  4. 4. What does calling Thread.interrupted() twice in a row return, if the current thread was interrupted once?

    The static Thread.interrupted() returns the flag and clears it, so the second call sees false. The instance method isInterrupted() does not clear the flag.
  5. 5. Your program needs a high-priority thread to always run before a low-priority one. Is setPriority enough?

    Scheduling with priorities is platform-dependent (HotSpot on Linux ignores them by default). Correctness must never depend on them.

Summary

  • Thread.State has six values: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED; getState() returns a snapshot for monitoring, not coordination.
  • RUNNABLE includes "ready to run" and often blocking I/O; BLOCKED means waiting for a synchronized lock.
  • Thread dumps (jcmd <pid> Thread.print, jstack) show every thread's state and stack.
  • Priorities (1โ€“10, default 5) are inherited hints that the OS may ignore; never rely on them.
  • interrupt() sets a flag and wakes interruptible blocking calls with InterruptedException, which clears the flag.
  • Check isInterrupted() in loops; Thread.interrupted() also clears the flag.
  • Never swallow InterruptedException: rethrow it, or restore the flag with Thread.currentThread().interrupt().

Next: Synchronization and Race Conditions, where threads start sharing data and you learn to keep it consistent.