Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a delay in Java?

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

while (true) {     if (i == 3) {         i = 0;     }      ceva[i].setSelected(true);      // I need to wait here      ceva[i].setSelected(false);      // I need to wait here      i++; } 

I want to build a step sequencer and I'm new to Java. Any suggestions?

like image 270
ardb Avatar asked Jun 08 '14 08:06

ardb


People also ask

Is there a wait command 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.

How do you make a delay loop in Java?

Delay loops can be created by specifying an empty target statement. For example: for(x=0;x<1000;x++); This loop increments x one thousand times but does nothing else.

How do I put Java to sleep?

The java. lang. Thread. sleep(long millis) method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.


1 Answers

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1); 

To sleep for one second or

TimeUnit.MINUTES.sleep(1); 

To 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 and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {     final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();     executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS); }  private static void myTask() {     System.out.println("Running"); } 

And in Java 7:

public static void main(String[] args) {     final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();     executorService.scheduleAtFixedRate(new Runnable() {         @Override         public void run() {             myTask();         }     }, 0, 1, TimeUnit.SECONDS); }  private static void myTask() {     System.out.println("Running"); } 
like image 90
Boris the Spider Avatar answered Oct 03 '22 07:10

Boris the Spider