How to Kill a Thread Effectively without Using the Deprecated Thread.stop() Method
The Java Thread class provides the stop() method as a means to terminate a thread, but it has been deprecated and should not be used. This article presents an alternative approach to terminating a thread using the interrupt method.
Using Interrupt to Stop a Thread
Instead of directly calling stop(), which is unsafe and can cause data corruption, we can use interrupt to signal to the thread that it should gracefully terminate. Here's how it works:
public class InterruptedExceptionExample { private static volatile boolean shutdown = false; public static void main(String[] args) { Thread thread = new Thread(() -> { while (!shutdown) { try { System.out.println("Running..."); Thread.sleep(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); thread.start(); System.out.println("Press enter to quit"); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } shutdown = true; thread.interrupt(); } }
In this code:
Advantages of Using Interruption:
Interrupting a thread offers several advantages over the deprecated stop():
The above is the detailed content of How to Safely Stop a Java Thread Without Using `Thread.stop()`?. For more information, please follow other related articles on the PHP Chinese website!