Thread Interruption as an Alternative to Stop()
The "stop()" method is generally discouraged in Java due to its potential for causing unexpected side effects. An alternative approach to terminating a thread is through interruption.
Thread Interruption
Interrupting a thread signals to it that it should halt its execution gracefully. To interrupt a thread, call its "interrupt()" method. If the thread is well-behaved and properly handles interruptions, it will attempt to finish its current task before exiting.
Sample Implementation
Consider the following code:
Thread thread = new Thread(new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(5000); System.out.println("Hello World!"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("Thread interrupted"); } } } });
In this code, the thread checks its interrupted status inside the loop. When interrupted, it throws an "InterruptedException," which is handled and sets the thread's interrupt status again. The thread then exits the loop and terminates.
Considerations
Distinguishing from "Thread#isAlive() and Thread#interrupted()
The above is the detailed content of Is Thread Interruption a Better Alternative to the Deprecated `stop()` Method in Java?. For more information, please follow other related articles on the PHP Chinese website!