When an Thread.interrupt() is called on some thread, what happens? [duplicate]

这一生的挚爱 提交于 2019-11-30 02:45:23

问题


When an Thread.interrupt() is called on some thread, what happens to that thread?


回答1:


The target thread is "interrupted". Mostly, a flag is set in that thread, which the thread can look at (with Thread.interrupted()). If the target thread was currently blocked on some I/O or Object.wait(), then it is awakened with, respectively, an InterruptedIOException or an InterruptedException.

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop(), which is more like shooting the thread with an assault rifle.




回答2:


The Javadoc for that method explains what happens in what situation.




回答3:


Here is the JDK 1.6 Javadoc:

Interrupts this thread.

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.




回答4:


ZeissS is correct, signaling is the cleanest way to do it. you can also catch the interrupt exception and clean up that way.



来源:https://stackoverflow.com/questions/2289885/when-an-thread-interrupt-is-called-on-some-thread-what-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!