Possible Duplicate:
When does Java's Thread.sleep throw InterruptedException?
I saw we have to catch InterruptedException in the Thread.Sleep method, why? I never saw this exception occured in the real time. Any clue?
Possible Duplicate:
When does Java's Thread.sleep throw InterruptedException?
I saw we have to catch InterruptedException in the Thread.Sleep method, why? I never saw this exception occured in the real time. Any clue?
This happens if thread#1 is sleeping, and another thread interrupts it. This is usually an attempt to stop thread#1. For example, thread#1 is sleeping while doing some long-running task (perhaps in background) and the user hits a cancel button.
The IterruptedExeption
is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status!
{
throw new InterruptedException();
}
Every thread has a Boolean property associated with it that represents its interrupted status. The interrupted status is initially false; when a thread is interrupted by some other thread through a call to Thread.interrupt(), one of two things happens. If that thread is executing a low-level interruptible blocking method like Thread.sleep(), Thread.join(), or Object.wait(), it unblocks and throws InterruptedException. Otherwise, interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested to stop what it is doing; the interrupted status can be read with Thread.isInterrupted() and can be read and cleared in a single operation with the poorly named Thread.interrupted(). See.
There is no way to simply stop a running thread in java (don't even consider using the deprecated method stop()
). Stopping threads is cooperative in java. Calling Thread.interrupt()
is a way to tell the thread to stop what it is doing. If the thread is in a blocking call, the blocking call will throw an InterruptedException
, otherwise the interrupted flag of the thread will be set.
The problem is that blocking calls like sleep()
and wait()
, can take very long till the check can be done. Therefore they throw an InterruptedException
. (However the isInterrupted
is cleared when the InterruptedException
is thrown.)