How can I add a delay in Java using sleep in a while loop?

I’m working on a step sequencer in Java and need to introduce a delay within a while loop.

Specifically, I want the program to pause execution at certain points before continuing.

Here’s the loop I’m using:

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 need a way to make the program pause execution at the indicated points. What’s the best way to achieve this using Java sleep?

If you just need a straightforward way to pause execution, Thread.sleep() is the easiest solution. This method pauses the thread for a specified time in milliseconds.

Here’s how you can modify your code:

while (true) {
    if (i == 3) {
        i = 0;
    }

    ceva[i].setSelected(true);
    
    // Pause for 500 milliseconds
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    ceva[i].setSelected(false);

    // Pause for another 500 milliseconds
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    i++;
}

This method blocks execution, meaning nothing else in the thread will run during the sleep period. If that works for your sequencer, then Thread.sleep() is a great option.

If you need more control over delays and want to avoid blocking the main thread, ScheduledExecutorService is a great alternative. This approach schedules tasks at fixed intervals.

Here’s how you can implement it:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class StepSequencer {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        scheduler.scheduleAtFixedRate(() -> {
            int i = 0;
            if (i == 3) {
                i = 0;
            }

            ceva[i].setSelected(true);

            try {
                Thread.sleep(500); // Sleep inside the task if needed
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ceva[i].setSelected(false);
            i++;
        }, 0, 1, TimeUnit.SECONDS); // Runs every second

    }
}

Another approach is to use Timer and TimerTask to schedule periodic execution without blocking the main thread.

Here’s how:

import java.util.Timer;
import java.util.TimerTask;

public class StepSequencer {
    static int i = 0;

    public static void main(String[] args) {
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (i == 3) {
                    i = 0;
                }

                ceva[i].setSelected(true);

                try {
                    Thread.sleep(500); // Pause
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                ceva[i].setSelected(false);
                i++;
            }
        }, 0, 1000); // Run every second
    }
}

This method is:

:white_check_mark: Good for periodic execution. :white_check_mark: Non-blocking since it runs in a separate thread. :white_check_mark: Easier to manage compared to a manual while loop.