What does java.lang.Thread.interrupt() do?

前端 未结 9 2396
日久生厌
日久生厌 2020-11-22 06:01

Could you explain what java.lang.Thread.interrupt() does when invoked?

9条回答
  •  日久生厌
    2020-11-22 06:54

    If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

    It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

    It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

提交回复
热议问题