Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

InterruptedException in multi threading

 
shankara me
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi !
My doubt is on InterruptedException in java .
I am asking my doubt based on sleep method in java.
When we call interrupt on a thread which is in sleep state then InterruptedException is thrown.
Below are my doubts:
1)Imagine that we have called interrupt method on a thread named Thread1,which has come out from a sleep.
Then will Thread1 throws InterruptedException?
2)Imagine that we have called interrupt method on a thread named Thread2,which will go to sleep.
That means now Thread2 is not in sleep state.
Then will Thread2 throws Interrupted exception?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it and see.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shankara me wrote:Hi !
My doubt is on InterruptedException in java .
I am asking my doubt based on sleep method in java.
When we call interrupt on a thread which is in sleep state then InterruptedException is thrown.
Below are my doubts:
1)Imagine that we have called interrupt method on a thread named Thread1,which has come out from a sleep.
Then will Thread1 throws InterruptedException?

That depends on if Thread1 does something else that can be interrupted and throws an InterruptedException. If not, then no, calling interrupt() on a thread will only cause an InterruptedExcetpion if whatever action is being performed reacts to an interrupt with that exception. If Thread1 comes out of sleep() before the interrupt(), and doesn't do anything else which throws the InterruptException, then no InterruptException will be thrown.


2)Imagine that we have called interrupt method on a thread named Thread2,which will go to sleep.
That means now Thread2 is not in sleep state.
Then will Thread2 throws Interrupted exception?

Yes, probably. Calling an interrupt() on a thread sets an 'interrupted' flag. Assuming you don't do anything in Thread2 that resets that flag before calling sleep() then when Thread2 calls sleep() the sleep() method will react like it was interrupted and will throw the InterruptedException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic