Java: Difference in usage between Thread.interrupted() and Thread.isInterrupted()?

后端 未结 9 704
南旧
南旧 2020-12-12 16:28

Java question: As far as I know, there are two ways to check inside a thread whether the thread received an interrupt signal, Thread.interrupted() and Thr

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 16:41

    interrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.

    A common error is to call a static method on an instance.

    Thread myThread = ...;
    if (myThread.interrupted()) {} // WRONG! This might not be checking myThread.
    if (myThread.isInterrupted()) {} // Right!
    

    Another difference is that interrupted() also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false even if the first call returned true.

    The Javadocs tell you important things like this; use them often!

提交回复
热议问题