Video in progress
How do you stop a thread the right way? How does interrupt() work?
Thread.stop() is dangerous and no longer works since Java 20. The right way is interrupt(): it sets a "stop" flag on the thread, and the thread has to check it itself and exit cleanly.
📖 Answer
interrupt() doesn't force anything, it only asks. There are two cases:
- If the thread is in a wait such as
sleep,wait,joinorBlockingQueue.take, it gets anInterruptedExceptionright away. - If the thread is busy computing, only the flag is set, and the thread has to check it itself with
Thread.currentThread().isInterrupted().
Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Job job = queue.take();
job.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag
break;
}
}
log.info("worker to'xtadi");
};
Important: when an InterruptedException is thrown, the flag is cleared. That is why it is a habit to call interrupt() again in the catch, so the code above this one also knows a stop was requested.
ExecutorService.shutdownNow() and Future.cancel(true) also send exactly this interrupt(). If your task doesn't respond to an interrupt, they can't stop it either.
Sign up to mark studied questions and save your progress.