beginnerFoundations

How do you safely stop a running thread in Java?

The correct approach is cooperative cancellation using interruption rather than forcibly terminating the thread. The thread's own run loop periodically checks a flag, typically written as while (!Thread.currentThread().isInterrupted()) { doWork(); }, and another thread signals it to stop by calling thread.interrupt(). If the thread happens to be blocked in a call like sleep() or wait() when interrupted, that call throws InterruptedException immediately, which the thread should catch, use to restore the interrupt flag, and then use as a signal to break out of its loop. You should never use the deprecated Thread.stop() method, because it forcibly kills the thread in the middle of whatever it was doing, which can leave shared data structures in an inconsistent, partially updated state -- comparable to yanking the power cord out of a running computer.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What does it mean for a lock to be reentrant?← Back to all Java Concurrency & Multithreading questions