• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does Thread.interupt() work?

 
Chris Gastin
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to understand how interupt() method will effect my ProcessorThread. I have started the thread, and as you can see it executes a for loop. If this thread is sleeping, and I call interupt then I know that an InterruptedException is thrown, and because of my structure it will stop running. What happens if this thread is not sleeping. It is in the middle of executing the for loop, and the interupt method is call on this thread? Will it finish executing or is the thread interupted in the middle of a run.

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the thread is running, no exception is thrown, but the "interrupted" flag of the Thread object is set. Your code can call the static method Thread.interrupted() to check if this flag is set for the current Thread. If it is, you can respond however you'd like; by convention, of course, your thread should clean up and exit.
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that if you don't check the interrupt status manually via Thread.interrupted() but the thread is interrupted while your code is running, an InterruptionException will be thrown immediately the next time you invoke Thread.sleep(). That's a good behavior and a common one in classes that are meant to block gracefully in a multithreaded environment, such as Selector where a call to wakeup() will affect the next call to select() if a select() isn't already in progress.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!