How exactly does Thread.interrupt() and Thread.interrupted() work? [duplicate]

*爱你&永不变心* 提交于 2019-12-02 12:26:22

When some other thread calls Thread.interrupt() the method sets Thread's interrupt status flag (initially false) to true. If the Thread is in blocking method like Thread.sleep(), Thread.join() or Object.wait() it unblocks and throws an InterruptedException.

Thread.interrupted() is a static method which can be use to check the current value of interrupt status flag, true or false. It also clears the interrupt status , setting the flag to false. That is calling it twice in a row may likely return false the second time even if it returned true the first time (unless the thread were interrupted again, setting the interrupt status flag to true after the first call)

Note a third method Thread.isInterrupted() which can check the interrupt status without resetting.

Typical use cases:

  1. Break exceptionally from a blocking operation
  2. Determine if it is desired to continue a long sequence of instructions at some logical save/stop point
  3. Determine if it is desired to continue a sequence of instructions prior to beginning a long running task
  4. Stop executing an iterative process that would otherwise continue into perpetuity (while(true) is bad, while(!Thread.interrupted()) is better)

You can use Thread.interrupt() to tell a thread to stop. When that thread performs a some blocking operations or checks the flag it trigger it to throw an InterruptedException to either wake up the thread or stop it.

While the purpose of interrupt() is usually to stop a thread, it doesn't mean it will. The interrupt can be ignored for long periods of time or completely ignored. If it triggers an InterruptedException this can be caught and loggged (or ignored) rather than stopping the thread.

Note: For threads in an ExecutorService, interrupting a task interrupts the thread and the ExecutorService catches this by design and doesn't shutdown the thread.

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