java thread interrupt

The thread interruption in java is not to terminate the thread, but to notify the thread whether to be interrupted through a state, whether the thread is interrupted or not is to be determined by the thread itself, not executed by an external thread.

interrupt method, to set the thread interrupt bit to true, the default is false

isInterrupt method, to determine whether the thread is interrupted, interrupt true

The interrupted method determines whether the thread is interrupted and clears the interrupted state, that is to say, if it is called twice in a row, the second time must be false

 

Since java cannot forcibly terminate the thread (the stop method has been deprecated), the interrupt method can be used to suggest thread termination (similar to gc, both are suggestions, haha), mainly to talk about this method, this method does not have threads during runtime Any impact, that is, the thread during the runtime will ignore this status bit and still run its own. Only when the thread is blocked, an InterruptedException will be thrown to exit the thread. It can be seen here that java Thread blocking is generally done through methods such as wait, sleep, join, etc. Similarly, these methods will throw InterruptedException exceptions

To sum up, the interrupt method only changes the state of the thread and cannot directly terminate the thread. Similarly, if the thread is running, it cannot be terminated. Only the blocked thread will throw InterruptedException to terminate the thread in this way.

 



 The above example shows that the thread at runtime cannot interrupt the thread through the interrupt method, but only changes the status bit

 



1 The example shows that in the running state of the thread, the isInterrupted method can be used to determine whether to perform business operations. The external thread calls the interrupt interrupt method of the thread, and the thread terminates the business by obtaining the interrupt status bit of the thread.

2 If the sleep method inside the thread is enabled above, this time is similar to the process and blocked. At this time, if the external thread calls the interrupt interrupt method of the thread, the thread immediately throws InterruptedException, we can use the exception to terminate the thread, and Clean up some resources in finally and so on

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326018025&siteId=291194637