• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interrupt()

 
Tony kunds
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Reply
  • Bookmark Topic Watch Topic
  • New Topic