Home >Java >javaTutorial >How to Safely Terminate a Thread in Java Without Using `stop()`?
How to Terminate a Thread without Using stop()
Using the stop() method to terminate a thread can lead to unpredictable behavior. This article presents an alternative approach to thread termination using interruption.
Alternative to stop()
Unlike stop(), interruption signals the thread to gracefully end its execution. Interruption is achieved through the Thread.interrupt() method. When a thread is interrupted, it will throw an InterruptedException.
Implementation Example
Consider the following code:
public class HelloWorld { public static void main(String[] args) throws Exception { Thread thread = new Thread(new Runnable() { public void run() { try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(5000); System.out.println("Hello World!"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); thread.start(); System.out.println("press enter to quit"); System.in.read(); thread.interrupt(); } }
In this example, the thread is created and started as usual. When the user presses Enter, the main thread interrupts the worker thread using thread.interrupt(). The worker thread handles the interruption by throwing an InterruptedException and then clearing the interrupted flag. Since the thread is checking for interruption within a loop, it will eventually end its execution after completing the current iteration.
Considerations
The above is the detailed content of How to Safely Terminate a Thread in Java Without Using `stop()`?. For more information, please follow other related articles on the PHP Chinese website!