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

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

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

相关标签:
9条回答
  • 2020-11-22 06:54

    Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

    Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

    Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

    EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

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

    EDIT (from @thomas-pornin's answer to exactly same question for completeness)

    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() that is more like shooting the thread with an assault rifle.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 06:54

    Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

    0 讨论(0)
提交回复
热议问题