Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get exception when using Thread.sleep(x) or wait()

Tags:

java

sleep

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?

like image 824
vincent low Avatar asked Jul 27 '10 10:07

vincent low


People also ask

Why does thread sleep threw an exception?

Because if a Thread is sleeping, the thread may be interrupted e.g. with Thread. interrupt() by another thread in which case the sleeping thread (the sleep() method) will throw an instance of this InterruptedException . Example: Thread t = new Thread() { @Override public void run() { try { System.

How do I use wait instead of thread sleep?

Difference between wait() and sleep() The major difference is that wait() releases the lock while sleep() doesn't release any lock while waiting. wait() is used for inter-thread communication while sleep() is used to introduce a pause on execution, generally.

What is difference between sleep () and wait ()?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization.

What are the wait () and sleep () methods?

At the time of the Synchronization, the Wait() method releases obj. At the time of the Synchronization, the Sleep() method doesn't release the obj, i.e., lock. 5. We can call the Wait () method only from the Synchronized context.


2 Answers

You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:

try {     Thread.sleep(1000);                 //1000 milliseconds is one second. } catch(InterruptedException ex) {     Thread.currentThread().interrupt(); } 
like image 175
Konrad Garus Avatar answered Oct 12 '22 02:10

Konrad Garus


As other users have said you should surround your call with a try{...} catch{...} block. But since Java 1.5 was released, there is TimeUnit class which do the same as Thread.sleep(millis) but is more convenient. You can pick time unit for sleep operation.

try {     TimeUnit.NANOSECONDS.sleep(100);     TimeUnit.MICROSECONDS.sleep(100);     TimeUnit.MILLISECONDS.sleep(100);     TimeUnit.SECONDS.sleep(100);     TimeUnit.MINUTES.sleep(100);     TimeUnit.HOURS.sleep(100);     TimeUnit.DAYS.sleep(100); } catch (InterruptedException e) {     //Handle exception } 

Also it has additional methods: TimeUnit Oracle Documentation

like image 20
Alexander Ivanov Avatar answered Oct 12 '22 01:10

Alexander Ivanov