Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Delay/Wait

Tags:

How do I delay a while loop to 1 second intervals without slowing down the entire code / computer it's running on to the one second delay (just the one little loop).

like image 371
Gray Adams Avatar asked Dec 21 '11 07:12

Gray Adams


People also ask

How do you delay time in Java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.

What is wait () in Java?

Simply put, wait() is an instance method that's used for thread synchronization. It can be called on any object, as it's defined right on java. lang. Object, but it can only be called from a synchronized block. It releases the lock on the object so that another thread can jump in and acquire a lock.

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

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.


2 Answers

Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)

like image 197
COD3BOY Avatar answered Sep 19 '22 17:09

COD3BOY


It seems your loop runs on Main thread and if you do sleep on that thread it will pause the app (since there is only one thread which has been paused), to overcome this you can put this code in new Thread that runs parallely

try{    Thread.sleep(1000); }catch(InterruptedException ex){   //do stuff } 
like image 45
jmj Avatar answered Sep 23 '22 17:09

jmj