I'm learning Java and trying to understand what happens when I call Thread.sleep(). In this loop, the progress bar is updated and then the current thread pauses for one second:
while (counter <= 100) {
bar.setValue(counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
What does Thread.sleep() actually do? Why does Java require the try-catch block, and what is the difference between handling the exception with try-catch versus declaring or rethrowing it?
3 Answers
The sleep call only pauses the current thread; it does not pause the entire application. If this code runs on a graphical user interface thread, sleeping there can freeze the window and prevent the progress bar from repainting. A timer or background worker is generally better for updating a GUI periodically.
Also, make sure the loop changes counter somewhere. Otherwise, the condition remains true and the loop can continue indefinitely.
Thread.sleep(1000) pauses the currently running thread for at least 1,000 milliseconds. The operating system or Java runtime places that thread into a waiting state and wakes it later. It does not guarantee that the thread will continue at exactly one second, since scheduling delays can make it take longer.
The sleep method can throw InterruptedException, which is a checked exception in Java. Checked exceptions must be handled with try-catch or passed to the calling method by declaring them with throws. The exception usually occurs when another thread interrupts the sleeping thread.
A try block says, “run this code, because it might throw an exception.” The matching catch block says, “if that particular exception happens, handle it here.” In this example, e.printStackTrace() prints information about the interruption, but you could instead restore the interrupt status, stop the task, or perform some other appropriate cleanup.
The alternative is to let the exception move up to the method that called this code by declaring it, for example:
public void updateBar() throws InterruptedException {
Thread.sleep(1000);
}
That means the current method is not handling the problem and is making its caller responsible for handling it. It does not change how sleep itself works.

So the catch block usually will not run during normal execution, but it is required because another thread could interrupt the sleep?