How to stop a thread created by implementing runnable interface?
Codemia Knowledge Hub ·
To effectively manage threads in Java, particularly those created by implementing the `Runnable` interface, it's crucial to understand reliable and clean ways to stop them. Java does not provide a direct method to stop a thread as it did with the now-deprecated `Thread.stop()` method, as such actions can lead to resource inconsistencies and corruption. Instead, Java encourages the use of cooperative mechanisms to stop threads safely.
Understanding Thread Lifecycle Management
When you implement a thread using the `Runnable` interface, you define the `run()` method, which is executed in a separate call stack. A common requirement is to be able to stop this execution cleanly and predictably when needed.
Cooperative Thread Termination
A better approach is to implement a cooperative mechanism that checks the thread's status regularly and terminates if a particular condition is met. This involves:
- Using a Volatile Flag: A common pattern is to use a `volatile` boolean variable to indicate whether a thread should continue running or terminate. The `volatile` keyword ensures that the variable is visible to all threads that read it.
- Checking the Flag in the `run()` Method: Within the `run()` method, periodically check the flag's value and exit the loop or terminate execution if the flag indicates that the thread should be stopped.
Here is a simple example to illustrate this approach:
- A `volatile` boolean `running` is used to control the loop in the `run()` method.
- `Thread.sleep()` is used to simulate work being done and can be interrupted by the thread.
- The `stop()` method allows external control to signal the thread to stop.
- Restore Interrupt Status: If you catch an `InterruptedException`, and it's appropriate to stop the thread, you might want to signal the interruption to other parts of the program by calling `Thread.currentThread().interrupt()`.
- Graceful Termination: If a thread is performing a critical task and an interruption is detected, ensure no resources or locks are left in an inconsistent state.
- Controlled Shutdown: This method ensures you have full control over when a thread terminates and how to handle ongoing tasks.
- Avoiding Deprecated Methods: Rather than relying on `Thread.stop()`, this approach used properly aligned Java mechanisms fits well with the concurrency paradigm.
- Remain Aware of Synchronization: While using the `volatile` keyword ensures visibility of changes, ensure no other synchronization issues arise when your threads interact with shared data.
Related reading
- How to stop all the running threads, if one of those throws an Exception?
- How to stop BackgroundWorker correctly
- How to stop BackgroundWorker on Form's Closing event?
- How to sync data between master and slave node in distributed systems
- How to store printStackTrace into a string
- How To Stream Chunked Response With Spring Boot RestController
- How to sync data for a particular user, when reading from kafka?
- How to Sync iPhone Core Data with web server, and then push to other devices?
System design interview problems on this topic
- Design a Distributed Locking System: solution and walkthrough
- Design a Distributed Counter: solution and walkthrough
- Design Ticketmaster: solution and walkthrough
- Design a Flash Sale System: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseInterview Questions practice on Codemia
Over 11,000 interview practice questions for 300+ companies, searchable by company and role.