Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The Java documentation is not clear on this point. What happens if you call interrupt on a Thread before a call to Thread.sleep():

        //interrupt reaches Thread here
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            return;
        }

Will the InterruptedException be thrown?

Please point to relevant documentation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, it will throw an exception. According to the javadoc for Thread.sleep, the method:

Throws: InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

The 'has' in this case is an informal way of referring to the interrupted status. It's a shame that it is informal - if there's somewhere a spec should be precise and unambiguous, well, it's everywhere, but it's the threading primitives above all.

The way the interrupted status mechanism works in general is if that a thread receives an interruption while it's not interruptible (because it's running), then the interruption is essentially made to wait until the thread is interrupted, at which point it swoops in an causes an InterruptedException. This is an example of that mechanism.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...