There are 3 ways to terminate a running thread in Java
① thread exits normally, the run () method has finished executing
② uses the Stop () method in the thread class to forcibly terminate the thread. However, the Stop () method has expired and is not recommended for use
③ using interrupt mechanism interrupt ()
1.stop () method
Stop () has been deprecated in Java multi-threading
1.stop () method can cause undesirable consequences of releasing locks, incomplete data
For example, a locking method:
Threada threads have monitors that are responsible for protecting certain critical resources, such as the amount of money transferred by a bank. When the transfer process is in progress, the main thread calls the Threada.stop () method or This.stop (). As a result, the monitor is released and the resources it protects (the amount of money transferred) are likely to show inconsistencies. For example, the a account was reduced by 100, while the B account did not increase by 100, and there was no guarantee of data atomicity
2. When the thread calls the Stop () method, all operations of the thread are terminated immediately, and a Threaddeath exception is thrown , usually without capturing
2.interrupt () interrupt mechanism
This method is an instance method, but it does not really break a running thread, but instead gives the thread a stop mark and requires a graceful termination of the thread with judgment.
Run code
Output results
As you can see,interrupt () doesn't really stop the running thread, so how do I stop the thread?
3. Determine the stopping state of a thread
The interrupted () method and the Isinterrupted () method can reflect the terminating state of the current thread
Look out interrupted () is a static method and isinterrupted () is an instance method
1.interrupted () method
It can be seen from above that interrupt () executes the thread Interrupted () method The first call returns True, and the second call returns False, which is viewed here Interrupted () source found that the method will clearly interrupt the state
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);
source found the method interrupted () will call isinterrupted method to pass in the parameter clean state, call the change method, the method inside will clear the interrupt state
2. isinterrupted() method
Continue to create RUN3 based on the example above
Summed up the differences between the two judgment thread interrupts, the following begins gracefully interrupting the thread
Java multithreaded 5:java terminating thread and interrupt mechanism (STOP (), interrupt (), Interrupted (), isinterrupted ())