What does Thread.sleep() do, and why does it need try/catch?
Asked by
thermal.expansion
I'm learning Java and trying to understand how Thread.sleep(1000) works in this loop. The code updates a progress bar, pauses for one second, and catches InterruptedException if the thread is interrupted. Why does Java require the try/catch here? What is the difference between handling the exception with try/catch and declaring or throwing it instead? Also, does sleep pause the entire program or only the current thread?
Answers
Instead of catching the exception, a method can declare it with throws InterruptedException. That passes responsibility to the methodโs caller, which must then catch it or declare it again. In simple terms, try/catch means โIโll handle this here,โ while throws means โthe caller must handle this.โ You generally shouldnโt silently ignore an interruption.
Reply to this answer
InterruptedException is a checked exception in Java, so the compiler requires you to deal with it. A try/catch says, โrun this code, and if this particular exception happens, handle it here.โ In the example, e.printStackTrace() prints information about the interruption, although production code would usually decide whether to stop, clean up, or restore the interrupt status instead.
2Softbound: The catch block doesnโt make sleep work or make the delay happen. It only defines what your program should do if sleep is interrupted.
Reply to this answer
Thread.sleep(1000) pauses the currently running thread for at least about 1,000 milliseconds. It doesnโt necessarily pause the entire applicationโother threads can continue running. Internally, the runtime asks the operating system to put that thread into a waiting state and wake it later. The delay can be slightly longer because the thread still has to be scheduled again.
please define terms: The thread can also wake early if another thread interrupts it. Thatโs why sleep declares InterruptedException.
Reply to this answer
Add your answer
Answers are reviewed before publication.
2 dozen plums: Also, the sample loop needs to change counter somewhere, such as counter++, or it will keep running forever if counter starts at 0.