In Java, stopping a thread can be a bit tricky since the Thread.stop() method has been deprecated due to its unsafe nature. Instead, it is recommended to use a more controlled approach to stop a thread gracefully. This can be achieved by using a shared variable that the thread checks regularly to determine if it should terminate.
Here is an example of how to stop a thread in Java using a boolean flag:
public class StoppableThread extends Thread {
private volatile boolean running = true;
public void run() {
while (running) {
// Thread task
System.out.println("Thread is running");
try {
Thread.sleep(1000); // Simulating work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Thread has stopped");
}
public void stopThread() {
running = false;
}
public static void main(String[] args) throws InterruptedException {
StoppableThread thread = new StoppableThread();
thread.start();
Thread.sleep(5000); // Let the thread run for 5 seconds
thread.stopThread(); // Request to stop the thread
thread.join(); // Wait for the thread to finish
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?