The generally recommended method to terminate a thread is to let the thread end on its own and enter the Dead state, which means to execute the run() method. That is, if you want to stop the execution of a thread, you must provide some way for the thread to automatically end the execution of the run() method. For example, set a flag to control whether the loop is executed, and let the thread leave the run() method in this way.
1. Use Boolean flag bits
In the execution code of a thread, a Boolean flag is used to identify whether the thread needs to be terminated. During the execution process, the thread constantly checks this flag bit. If the flag bit is true, it will actively exit the loop or method executed by the thread, thereby terminating the thread's execution.
public class MyThread implements Runnable { private volatile boolean flag = true; public void run() { while (flag) { // Execute threaded tasks } } public void stopThread() { flag = false; } }
2. Use interrupt() method
Each thread object has an interrupt() method. By calling this method, the interrupt status of the thread can be set to "interrupt". In the execution code of a thread, use the().isInterrupted() method in the appropriate location to check the interrupt status of the thread and terminate the execution of the thread if necessary.
public class MyThread extends Thread { public void run() { while (!().isInterrupted()) { // Execute threaded tasks } } public void stopThread() { interrupt(); } }
3. Use the stop() method (outdated)
The Thread class provides a stop() method, which can immediately terminate the execution of the thread. However, this method is outdated and is not recommended. Because the stop() method may cause the thread to not release the occupied lock resources, causing thread safety issues.
public class MyThread extends Thread { public void run() { while (true) { // Execute threaded tasks } } public void stopThread() { stop(); } }
4. Use the () method with isInterrupted() method
The interrupt() method of the thread will set the interrupt status of the thread to "interrupt". In the execution code of a thread, you can use the().isInterrupted() method to check the interrupt status of the thread and terminate the thread execution if necessary. Compared with Method 2, this method is more flexible and can handle more complex thread termination logic.
public class MyThread extends Thread { public void run() { while (!().isInterrupted()) { try { // Execute threaded tasks // There may be some blocking operations, such as () etc. } catch (InterruptedException e) { //Catch InterruptedException exception and clear interrupt status ().interrupt(); } } } public void stopThread() { interrupt(); } }
This is the end of this article about the 4 ways to terminate java threads. For more related java thread termination content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!