How can we stop a thread in Java

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 } }

Java Thread Management Stop Thread Multithreading Thread Safety