Thread State Lifecycle Inspection
Walk a thread through NEW, RUNNABLE, TIMED_WAITING, and TERMINATED with getState, the states thread dumps report for stuck workers.
Code
public class ThreadStateTour {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("before start: " + worker.getState());
worker.start();
System.out.println("just started: " + worker.getState());
Thread.sleep(50);
System.out.println("while sleeping: " + worker.getState());
worker.join();
System.out.println("after join: " + worker.getState());
}
}What the code does
The code’s whole job belongs to the class ThreadStateTour.
Applying it
Running the file prints labeled results such as before start:, just started:, while sleeping: — each operation’s effect is visible in the output.
Statements that matter
Thread.currentThread().interrupt();
Thread.sleep(300);
Thread.sleep(50);
Interactive Tools for This Topic
FAQ
- What does Thread State Lifecycle Inspection print when run?
- Invoke the file as-is — the `before start:`, `just started:`, `while sleeping:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.