how can the statement interrupt() forces the thread to stop() is true i appreciate any link to interrupt() and InterruptedException. I know that interrupt() is called on a sleeping thread. my question is when will a thread throw an InterruptedException and when will it stop the Thread. -thanks in advance
In general, interrupting a thread is the proper way to "stop it." In fact, an interruption, by its very nature, is a great way of "getting the attention" of a thread, whether it is sleeping or processing. Take the following example:
You'll notice that, in either case, you can break out of the run method by interrupting the thread. The difference is that, if the thread is not sleeping, you'll have to do a check on your own, like I did here. Also, if you get stuck in a long loop, it's possible that you might not check for the interruption for some time, as was the case in this example. Therefore, if you have a thread that you'd like to be able to interrupt often, you'll want to design that thread with that in mind. I hope this helps, Corey
A thread on which Object.wait , Thread.join or Thread.sleep were invoked can be interrupted. All of these methods must be used knowing that they could throw a cheked exception: InterruptedException if Thread.interrup is invoked. Otherwise it's possible to check as, Corey did, with Thread.isInterrupted
Post by:autobot
If you're gonna buy things, buy this thing and I get a fat kickback:
a bit of art, as a gift, that will fit in a stocking