Threads · Topic 3 of 7
Thread states
Definition​
A thread is in one of a few states: NEW (created, not started), RUNNABLE (running or ready), BLOCKED (waiting for a lock), WAITING or TIMED_WAITING (waiting for another thread or a timer), and TERMINATED (finished).
Example code​
Watching one thread move through its states
class Demo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(300); // the thread waits with a timer
} catch (InterruptedException ignored) { }
});
System.out.println(worker.getState()); // NEW
worker.start();
Thread.sleep(100);
System.out.println(worker.getState()); // TIMED_WAITING: it is inside sleep
worker.join();
System.out.println(worker.getState()); // TERMINATED
}
}
// Output:
// NEW
// TIMED_WAITING
// TERMINATED
Finished this page? Track your progress (saved only in your browser).