I get exception when using Thread.sleep(x) or wait()
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();
}
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
Have a look at this excellent brief post on how to do this properly.
Essentially: catch the InterruptedException
. Remember that you must add this catch-block. The post explains this a bit further.