Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread Sleep and Interrupted Exception

  1. Why does a sleep thread need a try catch to catch Interrupted Exception?
  2. Why does a sleep even emit an Interrupted Exception error? This are the two questions I really wanna find out about in java programming I've been searching through google and i've still haven't found a clear explanation is to why this two things happen.
like image 298
Jericho Aganon Avatar asked Mar 20 '13 15:03

Jericho Aganon


2 Answers

  1. Because a Thread cant complete its normal execution if you Interrupt it, and you need to catch that in order to be prepared to do something.
  2. Because a thread waiting is different from an interrupted thread, a thread waiting can be resumed, but an interrupted thread is already finish execution.
like image 83
jsedano Avatar answered Sep 23 '22 23:09

jsedano


An InterruptedException is thrown when the thread is blocked/waiting and it is interrupted by another thread (by means of Thread.interrupt). Think of it as a request for immediate termination, that do not suffer the drawbacks of Thread.stop().

This way, even if you instruct a thread to sleep for several years, you are able to interrupt that thread.

The recommended practice is aborting whatever you are processing when a InterruptedException is thrown.

like image 37
Javier Avatar answered Sep 26 '22 23:09

Javier