I have tried to delay - or put to sleep - my Java program, but an error occurs.
I'm unable to use Thread.sleep(x)
or wait()
. The same error message appears:
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.
Is there any step required before using the Thread.sleep()
or wait()
methods?
My ways to add delay to a Java program.
This is for sequential delay but for Loop delays refer to Java Delay/Wait.
Try this:
eg:-
Use
java.util.concurrent.TimeUnit
:Sleep for one second or
Sleep for a minute.
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use
sleep
.Further,
sleep
isn't very flexible when it comes to control.For running a task every second or at a one second delay I would strongly recommend a [
ScheduledExecutorService
][1] and either [scheduleAtFixedRate
][2] or [scheduleWithFixedDelay
][3].To run the method
myTask
every second (Java 8):Put your
Thread.sleep
in a try catch blockThread.sleep()
is simple for the beginners and may be appropriate for unit tests and proofs of concept.But please DO NOT use
sleep()
for production code. Eventuallysleep()
may bite you badly.Best practice for multithreaded/multicore java applications to use the "thread wait" concept. Wait releases all the locks and monitors held by the thread, which allows other threads to acquire those monitors and proceed while your thread is sleeping peacefully.
Code below demonstrates that technique:
DelayUtil
implementation: