How can I make a Java program sleep between iterations?

I want my program to count up to 10 with a 1-second pause between each number.

However, I’m getting an error in Eclipse: “thread cannot be resolved.”

How should I correctly use sleep in Java in this loop to avoid errors?

This is the most straightforward way to pause execution.

public class SleepExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
            try {
                Thread.sleep(1000); // Pause for 1 second
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // Restore interrupted status
            }
        }
    }
}

It’s simple, and the try-catch prevents compilation errors.

If you prefer a more readable and self-explanatory approach:

import java.util.concurrent.TimeUnit;

public class SleepExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
            try {
                TimeUnit.SECONDS.sleep(1); // More readable
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
  • TimeUnit.SECONDS.sleep(1) is clearer than Thread.sleep(1000).

For a more advanced and flexible approach:

import java.util.concurrent.*;

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

        Runnable task = new Runnable() {
            private int count = 1;

            @Override
            public void run() {
                if (count > 10) {
                    scheduler.shutdown(); // Stop execution
                    return;
                }
                System.out.println(count++);
            }
        };

        scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
    }
}

This is non-blocking, meaning your program can do other tasks in parallel.