Java Thread Sleep and Interrupted Exception

2019-04-06 00:14发布

问题:

  1. Why does a sleep thread need a try catch to catch Interrupted Exception?
  2. Why does a sleep even emit an Interrupted Exception error? This are the two questions I really wanna find out about in java programming I've been searching through google and i've still haven't found a clear explanation is to why this two things happen.

回答1:

1.- Because a Thread cant complete its normal execution if you Interrupt it, and you need to catch that in order to be prepared to do something. 2.- Because a thread waiting is different from an interrupted thread, a thread waiting can be resumed, but an interrupted thread is already finish execution.



回答2:

An InterruptedException is thrown when the thread is blocked/waiting and it is interrupted by another thread (by means of Thread.interrupt). Think of it as a request for immediate termination, that do not suffer the drawbacks of Thread.stop().

This way, even if you instruct a thread to sleep for several years, you are able to interrupt that thread.

The recommended practice is aborting whatever you are processing when a InterruptedException is thrown.



回答3:

When you ask a thread to sleep, the expected behavior for that thread is to sleep for that much time. So if the sleep is interrupted, it will throw InterruptedException to indicate that it couldn't complete the task. And you might want to take care of what should be done if it is Interrupted.



回答4:

There is a clean example of how the Interrupted Exception can be thrown here : http://www.javamex.com/tutorials/threads/thread_interruption.shtml

And a discuss about sleep() and yield() here : http://www.coderanch.com/t/508657/threads/java/Sleep-Yield-state



回答5:

It's because sleep() could potentially block forever/a long time so you need a way to be able to cancel this behaviour. Because it is not "normal" completion when you interrupt the action you may need to perform some specific compensating or remedial action, e.g., to send an alert that you never received a notification, clean up resources, etc.
There is a pretty good developer works article on the subject.



回答6:

Sleep and interrupts are not related semantically. It's just that Java designers thought that when you want your thread to sleep, it's a good opportunity to remind you about interrupts. This is like Duke saying "It looks like you're trying to sleep, would you also like to make your thread a good citizen by making sure that it responds to interrupt events properly, when the need for a way to get it to terminate abruptly at a later stage in your project arises?"

So one will often see code like this:

try {
    Thread.sleep(1000);
} catch (InterruptedException ie) {
    //Don't worry about it.
}

Sometimes people say this is considered bad practice. But if you're not planning to use the interrupts facility in your program, then these exceptions will never be thrown, so you have to ask yourself whether doing the extra work in order to take care of these exceptions, in case you decide to add the interruptibility feature to your program some time later, makes sense. This is one of those things that Java designers insisted that every thread should do — that you could interrupt() it, and it will quickly and cleanly abort what it's doing. I think that's unnecessary in many cases, but people will look at your code, see this and still say "eew, bad practice!"

The official Java tutorial explains interrupts. Basically, if you have one thread t doing some processing, and then the user wants to cancel it, from another thread you would call t.interrupt(). In the code that's running on thread t, whenever it sleep()s, or wait()s, etc., an InterruptedException will be thrown. If it doesn't do any of these, then it can (should) also find out if it had been interrupted using Thread.interrupted() from time to time. In all these ways of finding out about interrupts, it should abandon what it's doing and clean up ASAP. (That is to say: if it does so, then this behaviour might be useful to you or someone — that's the idea of interrupts.)

So, Java makes this a checked exception of the sleep(..) method, to force you to think about using this facility. The other part of the rationale is that if sleep(..) is interrupted, then it will wake up early, and that's an exceptional event. (But remember, there's that "if".)

The important thing is that interrupts don't just happen for no reason. They happen if you write code to make them happen, or if someone else does, who launches your threads and has a need to cancel their activities. So this is who causes Thread.sleep(..) to throw an InterruptedException. You do. And if you don't, then you still need to catch it.


Edit. By the way, it would be a better practice to do it this way:

try {
    Thread.sleep(1000);
} catch (InterruptedException ie) {
    throw new UnsupportedOperationException("Interrupts not supported.", ie);
}

So, if you, or somebody else, ever tries to interrupt this thread by mistake later, then when they go to test it, they will be reminded that this feature is not implemented. (UnsupportedOperationException is a subclass of RuntimeException, so it's unchecked.)