admin管理员组

文章数量:1612404

	在编写完代码后,我习惯性的用IDEA的SonarLint插件检查了一遍代码。
结果在我catch (InterruptedException e)的地方做了预警。


原因是我没有在catch里边写Thread.currentThread().interrupt();
那为什么要写这个?

这是维持状态。
sleep()wait()方法抛出InterruptException异常后会清除中断标志,即把中断标志设为false。
而你又捕获InterruptException并吞下它,这时你基本上阻止任何更高级别的方法/线程组注意到中断。这可能会导致问题。
通过调用Thread.currentThread().interrupt(),你可以设置线程的中断标志(即把中断标志设为true),因此更高级别的中断处理程序会注意到它并且可以正确处理它。


接下来还要讨论一下在线程中调用Thread.interrupt()意味着什么?

参考资料

  1. Java里一个线程调用了Thread.interrupt()到底意味着什么?
  2. Shutting down Threads Cleanly
  3. https://blog.csdn/AlbertFly/article/details/52768590
  4. 为什么在catch InterruptException块中调Thread.currentThread.interrupt()?
  5. Thread.interrupt()方法理解

本文标签: threadcurrentThreadInterrupt