Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

In my Java code, I need something to wait/ delay for several 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. Can someone help me with this?

1 Answer

0 votes
by (13.1k points)
edited by

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

TimeUnit.SECONDS.sleep(1);

To sleep for on 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 ScheduledExecutorSerice and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second in 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");

}

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
+2 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...