Java thread interruption adopts the idea similar to CPU interruption. That is, the thread object has an int ID to indicate whether there is any interruption. 1 indicates yes, and 0 indicates no. The thread code detects the interrupt identifier and performs corresponding processing.
1. How to set the interruption status
If you need to set the interrupt ID to 1, call the thread's interrupt method. This method only sets the interrupt ID to 1, and does not perform other operations.
2. How to handle the interruption status
The code running in the 2.1 thread should constantly check whether there is any interruption, handle the problem accordingly, and reset the interrupt ID to 0. In general, ignore the interruption, or exit the program when there is an interruption.
Code in the 2.2 thread is being blocked (callingObject
Classwait()
,wait(long)
Orwait(long, int)
Method, Thread classjoin()
,join(long)
,join(long,
int)
,sleep(long)
Orsleep(long, int)
). When the interrupt mark is set to 1, the code blocks and throws an interrupt exception and automatically clears the interrupt status (resets the interrupt mark to 0 ). The thread code should respond to the interrupt exception.
Code in the 2.3 thread is blocked (NIO) on the resource that can be interrupted. When the interrupt ID is set to 1, there are two conditions (the interrupt status is not automatically clear ):
1) The resource can be interrupted and an exception occurs when the code is blocked.
2) an empty result is returned immediately.
In this case, the thread code must handle exceptions and interruptions.
3. Clear the interruption status
Call the interrupted method of the thread class. This method returns the current interrupt status and resets the interrupt ID to 0.
4. Special blocking interruption
The accept method of serversocket has been blocked, and its method will not be interrupted in this province. To interrupt blocking, you need to call the close method of serversocket. In this case, the accept method interrupts blocking and throws ioexception.