• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the purpose of interrupt() method of java.lang.Thread class?

 
kish kumar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


what is the functionality of interrupt() method ?

after calling it on say thread t , to which state this t goes?

how to resume a interrupted thread? resume() method has been deprecated

 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Threads and Synchronization.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interrupt is used to safely signal a Thread that it should stop (or at least interrupt) what it is doing. Calling the interrupt() method does not change the state of the Thread, it sets a flag to tell the Thread it has been interrupted. Certain API will respond to interrupts with an InterruptedException, things like wait() and Thread.sleep(). Others will not allow interruption. In your code it is always the programmer's responsibility to respond to the interruption, either (or both) by catching InterruptedExceptions, or regularly checking the interruption status of the Thread (currentThread.isInterrupted() or Thread.interrupted()).

You shouldn't reset the interrupt status of the Thread from outside the Thread. You can use the static method Thread.interrupted() to both check if the current thread was interrupted and to clear the interrupt flag.

Interrupts are not like Thread.stop(), or suspend() which force a Thread state and may stop a Thread from running. These methods (and the resume() method) are deprecated because they are unsafe. The interrupt flag puts the onus of stopping and pausing onto the Programmers, which allows them to ensure safety of the response to stop executing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic