W3docs

How do you kill a Thread in Java?

To stop a thread in Java, you can use the interrupt() method of the Thread class.

To stop a thread in Java, you can use the interrupt() method of the Thread class. This method sets the interrupted status of the thread, which can be checked using Thread.currentThread().isInterrupted(). Note that isInterrupted() checks the flag without clearing it, whereas Thread.interrupted() checks and clears the flag.

Here is an example of how you can use the interrupt() method to stop a thread:


class MyTask implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                // Simulate work or a blocking call
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // Restore interrupted status and exit the loop
                Thread.currentThread().interrupt();
                break;
            }
        }
    }
}

Thread thread = new Thread(new MyTask());
thread.start();

// ...

thread.interrupt();

In this example, a task is defined by implementing Runnable and overriding the run() method. The Thread constructor wraps the task, and start() launches it. The loop continues until the interrupted status is set. When interrupt() is called, it typically unblocks a waiting thread (like Thread.sleep()), throwing an InterruptedException. The catch block restores the interrupted status and breaks the loop to allow graceful termination.

Keep in mind that interrupt() does not stop the thread immediately. It simply sets the interrupted status and allows the thread to stop itself when convenient. It is up to the thread to periodically check the status or handle InterruptedException to exit gracefully.

You can also use the stop() method of the Thread class to stop a thread, but this method is generally considered unsafe and is deprecated.