What is the best way to introduce a delay in Java using the sleep method?
I’m building a step sequencer in Java and need to introduce a delay between iterations in a while loop. For example, I want to pause execution at certain points before proceeding to the next step. How can I achieve this using sleep Java, and what is the best way to implement it correctly?
Ah, the good old Thread.sleep()
! If you just need a simple pause, this does the job.
while (true) {
ceva[i].setSelected(true);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
ceva[i].setSelected(false);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
i = (i + 1) % ceva.length;
}
Why use this?
- Super simple & effective for basic delays.
- Works well for sequential logic where blocking the thread is okay.
Be careful!
Thread.sleep()
blocks the current thread, making it a poor choice for UI applications.
But what if you don’t want to block the main thread? Enter ScheduledExecutorService
…
If you want more control & don’t want to block your main thread, ScheduledExecutorService
is your friend.
import java.util.concurrent.*;
public class StepSequencer {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
Runnable stepTask = new Runnable() {
private int i = 0;
@Override
public void run() {
ceva[i].setSelected(true);
scheduler.schedule(() -> ceva[i].setSelected(false), 1, TimeUnit.SECONDS);
i = (i + 1) % ceva.length;
scheduler.schedule(this, 2, TimeUnit.SECONDS);
}
};
scheduler.schedule(stepTask, 0, TimeUnit.SECONDS);
}
}
Why use this?
- Non-blocking – lets the main thread remain free.
- More control over scheduling.
Best for:
- Multi-threaded apps.
- Running tasks in the background without freezing UI.
For repeating tasks, Timer
+ TimerTask
works well.
import java.util.Timer;
import java.util.TimerTask;
public class StepSequencer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
private int i = 0;
@Override
public void run() {
ceva[i].setSelected(true);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
ceva[i].setSelected(false);
}
}, 1000); // Delay deselecting by 1 second
i = (i + 1) % ceva.length;
}
}, 0, 2000);
}
}
Why use this?
- Easy to set up periodic execution.
- Great for animations, repeated sequences, or scheduled jobs.
Downsides?
- Less flexible than
ScheduledExecutorService
.
- Not ideal for complex, dynamic tasks.