Lifecycle and interruption
Read a thread’s state and stop one the only way Java supports: by asking it politely.
Open this lesson in the learning hubKey points
- Six states: NEW, RUNNABLE, BLOCKED (waiting for a lock), WAITING, TIMED_WAITING, TERMINATED.
- A finished thread cannot be restarted. Calling
start()twice throwsIllegalThreadStateException. Thread.stop()is dead. Since Java 20 it just throwsUnsupportedOperationException, because killing a thread mid-write corrupts state.interrupt()only sets a flag. Blocking calls likesleepandwaitnotice it and throwInterruptedException.- Never swallow
InterruptedException. Either exit the task, or callThread.currentThread().interrupt()to restore the flag.
Example
public class Main {
public static void main(String[] args) throws InterruptedException {
Object monitor = new Object();
Thread worker = new Thread(() -> {
try {
Thread.sleep(200); // TIMED_WAITING
synchronized (monitor) { monitor.wait(); } // WAITING
} catch (InterruptedException e) {
System.out.println("worker: interrupted, exiting cleanly");
}
}, "worker");
System.out.println("before start : " + worker.getState());
worker.start();
Thread.sleep(60);
System.out.println("while asleep : " + worker.getState());
Thread.sleep(300);
System.out.println("while waiting: " + worker.getState());
worker.interrupt(); // a request, not a kill
worker.join();
System.out.println("after join : " + worker.getState());
}
}
You never kill a thread. You ask it to stop, and it agrees.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Multithreading course, and every lesson in it is listed on the Multithreading contents page.