Since comments already link to the answers on the question why you should catch InterruptedException, I will focus on your second question - about the use of Thread.sleep()
.
This method is handy when you want to introduce a short pause into your thread execution. For example, imagine you have to update 100 000 rows in a database, but in order to lower the impact on the database you are required to introduce breaks of, say 2 seconds, between your update queries. One of the quick-and-dirty solutions will look like this:
for (int i = 0; i < 100 000) {
statement.executeUpdate(....);
Thread.sleep(2000);
}
Here you after each update you wait 2 seconds and only after that go to executing the next update. (remember is just an illustration of the concept, not full blown production-ready code to be copy-pasted).
Another typical situation happens when you wait for some resource to be available and do not want to waste CPU cycles while awaiting for it to become available. For example, you make an asynchronous call that returns a Future
and you want to wait for the the asynchronous computation to complete to go on with your logic. Its generally done like that:
int someNumberOfMillisToSleep = //some number;
...
while (!future.isDone()) {
Thread.sleep(someNumberOfMillisToSleep );
}
/*now that future.isDone() returned true,
you can get the result and go on with on with you logic
*/
int res = future.get();
//some computation here
So having nothing more important to do you sleep waiting for the asynchronous computation to be completed in order not generate useless load on the CPU.
It is also important that in contrast to wait
the method sleep
retains locks on the monitors that were acquired by the thread. That means you can use it in a synchronized block and expect the thread to be able to continue the work it was doing in this block after the sleep returns (of course, if the thread was not interrupted).