Hi, when a thread (in Non-Runnable state) gets interrupted by some other thread ,throws InterruptedException when transited to the Runnable state. My question is How one thread can be interrupted by some other thread. How does it happen practically,I mean can we do it,it happens accedently?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
author and iconoclast
It's just a way of sending a signal to a THread, to say "stop what you're doing." There won't necessarily be an Exception -- only if the THread was in the middle of a call to wait(), sleep(), or certain other methods. Otherwise, the interrupt() call will just set a flag that the Thread's runnable can check with isInterrupted().
So let's say you're overridden run() in a THread subclass; it might look like
Now any other thread can call interrupt() to stop this Thread.
It's very similar to that, but it's both more powerful (because it forces wait() and join() and sleep() to return immediately) and more dangerous (because if it does any of the above, it throws an InterruptedException and can thereby lob a spanner in the works of your logic.) I think it's less commonly used than it should be. I think it's not more widely used just because it's not widely understood.
I just grabbed my copy of Oaks and Wong's "Java Threads, 3rd Edition" (thanks, JavaRanch!) to see what they had to say. There's one page in Chapter 2 that says, in brief, that indeed, the interrupt flag can be used like a custom isRunning flag. They don't say that they think it's good or bad, just that it's an option.