How to pause execution
Short answer
Thread.sleep() pauses the current thread for the given number of milliseconds:
void main() throws InterruptedException {
IO.println("Starting...");
Thread.sleep(500);
IO.println("Done after half a second");
}Output:
Starting...
Done after half a secondsleep() can throw the checked InterruptedException, which is why main has throws.
With a Duration
Since Java 19 sleep() accepts a Duration — this makes the time unit obvious:
void main() throws InterruptedException {
for (int i = 3; i > 0; i--) {
IO.println(i);
Thread.sleep(Duration.ofMillis(300));
}
IO.println("Go!");
}Output:
3
2
1
Go!Repeating on a schedule
A ScheduledExecutorService runs a task at a fixed interval without blocking the main thread:
void main() throws InterruptedException {
var counter = new AtomicInteger();
try (var scheduler = Executors.newSingleThreadScheduledExecutor()) {
scheduler.scheduleAtFixedRate(
() -> IO.println("tick " + counter.incrementAndGet()), 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(500);
scheduler.shutdownNow();
}
}Output:
tick 1
tick 2
tick 3The task runs immediately and then every 200 ms; after half a second the scheduler is stopped. Usually there are three runs, but the exact number depends on how busy the computer is.
Common mistake
Swallowing InterruptedException with an empty catch. An interruption is a signal for the thread to stop, and it must not be lost. If you cannot rethrow the exception, restore the flag:
void main() {
Thread.currentThread().interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
IO.println("interrupted, stopping");
}
}Output:
interrupted, stoppingFunctions used in this recipe
- Thread.sleep() — Pauses the current thread for a given time.
- ExecutorService — A service that runs tasks on a pool of threads.