java.lang.Thread.interrupt()有什么作用?

java.lang.Thread.interrupt()有什么作用?,第1张

java.lang.Thread.interrupt()有什么作用?

Thread.interrupt()
设置目标线程中断状态/标志。然后在该目标线程中运行的代码可以轮询中断状态并适当地处理它。一些诸如之类的方法
Object.wait()
可能会立即消耗中断状态并抛出适当的异常(通常为
InterruptedException

Java中的中断不是抢先的。换句话说,两个线程必须配合才能正确处理中断。如果目标线程未轮询中断状态,则该中断将被有效忽略。

通过

Thread.interrupted()
返回当前线程的中断状态并清除该中断标志的方法进行轮询。通常,线程然后可能会执行某些 *** 作,例如
throw InterruptedException

编辑(来自Thilo注释):一些API方法已内置中断处理。在我的头顶上,这包括。

  • Object.wait()/Thread.sleep()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.使用ClosedByInterruptException。

编辑(来自@

thomas-pornin
对完全相同的问题的回答,以确保完整性)

线程中断是微调线程的一种温和方法。它用来使线程有机会干净地退出,而不是

Thread.stop()
像用冲锋q射击线程一样。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5004192.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存