当某个线程上调用 Thread.interrupt() 时,会发生什么?
当在某个线程上调用 Thread.interrupt() 时,该线程会发生什么?
When an Thread.interrupt()
is called on some thread, what happens to that thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
目标线程被“中断”。大多数情况下,在该线程中设置一个标志,线程可以查看该标志(使用 Thread.interrupted())。如果目标线程当前在某些 I/O 或
Object.wait()
上被阻塞,则会分别通过InterruptedIOException
或InterruptedException< 唤醒它/代码>。
线程中断是轻推线程的一种温和方式。它用于给线程一个干净地退出的机会,而不是
Thread.stop()
,后者更像是用突击步枪射击线程。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 orObject.wait()
, then it is awakened with, respectively, anInterruptedIOException
or anInterruptedException
.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.该方法的 Javadoc 解释在什么情况下会发生什么。
The Javadoc for that method explains what happens in what situation.
这是 JDK 1.6 Javadoc:
Here is the JDK 1.6 Javadoc:
蔡司是正确的,发信号是最干净的方法。您还可以捕获中断异常并以这种方式进行清理。
ZeissS is correct, signaling is the cleanest way to do it. you can also catch the interrupt exception and clean up that way.