518

I am trying to do something in Java and I need something to wait / delay for an amount of 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 and I'm new to Java. Any suggestions?

lospejos
  • 1,958
  • 3
  • 19
  • 33
ardb
  • 5,525
  • 5
  • 13
  • 16

8 Answers8

1004

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

TimeUnit.SECONDS.sleep(1);

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

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

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}
Matthew Moisen
  • 14,590
  • 25
  • 104
  • 205
Boris the Spider
  • 57,395
  • 6
  • 106
  • 161
  • 1
    @Matthew Moisen I couldn't get this Java 8 example to run. What is App:: exactly? By changing myTask() to a runnable lambda it works: Runnable myTask = () -> {...}; – comfytoday Dec 05 '17 at 23:52
  • 3
    It's a method reference @comfytoday - I suggest starting with [the documentation](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html). – Boris the Spider Dec 06 '17 at 07:25
  • 1
    `TimeUnit.SECONDS.wait(1)` is throwing `IllegalMonitorStateException` in Java 8.1 build 31 on Windows 6.3. Instead, I'm able to use `Thread.sleep(1000)` without a try/catch. – John Jan 05 '18 at 19:31
  • You called `wait` not `sleep` @JohnMeyer. Be more careful. – Boris the Spider Jan 05 '18 at 20:05
  • 1
    In Java 8, in java.util.concurrent.TimeUnit you get ```Unhandled exception: java.lang.InterruptedExecution``` for the ```sleep(1)``` – Shai Alon Aug 14 '19 at 12:11
  • 1
    You must surround the ```TimeUnit.SECONDS.sleep(1);``` with ```try catch``` – Shai Alon Aug 14 '19 at 12:13
  • @ShaiAlon What can one usually have in that catch block ? – Stephane Aug 19 '19 at 14:23
  • If anyone is still struggling with this function, make the enclosing function that calls ```sleep()``` throw InterruptedException with ```throws``` and catch it where the function is being called. @Stephane Or simply enclose that statement in a try-catch to catch the InterruptedException and print the stack trace. – need_to_know_now Feb 21 '21 at 09:12
202

Use Thread.sleep(1000);

1000 is the number of milliseconds that the program will pause.

try
{
    Thread.sleep(1000);
}
catch(InterruptedException ex)
{
    Thread.currentThread().interrupt();
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Anju Aravind
  • 3,034
  • 2
  • 14
  • 21
29

Use this:

public static void wait(int ms)
{
    try
    {
        Thread.sleep(ms);
    }
    catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    }
}

and, then you can call this method anywhere like:

wait(1000);
Azeem
  • 7,659
  • 4
  • 22
  • 36
Hecanet
  • 391
  • 3
  • 3
11

You need to use the Thread.sleep() call.

More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Ruslan
  • 2,587
  • 1
  • 17
  • 25
5

Using TimeUnit.SECONDS.sleep(1); or Thread.sleep(1000); Is acceptable way to do it. In both cases you have to catch InterruptedExceptionwhich makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException inside. So your code would just include one line:

TimeUtils.sleepFor(1, TimeUnit.SECONDS);

See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here

Michael Gantman
  • 5,975
  • 1
  • 17
  • 34
  • 5
    Using `catch (InterruptedException e) { /* empty */ }` is **NOT** a sensible solution here. At the very least, you should provide some log information. For more information about the subject, see https://www.javaspecialists.eu/archive/Issue056.html – Marco13 Aug 19 '18 at 18:37
  • @Marco13 Actually due to your comment and comments from some other people I modified the method TimeUtils.sleepFor() and now it interrupts current thread. So, it is still convenient in a way that you don't need to catch the InterruptedException, but the interruption mechanism now works. – Michael Gantman May 10 '21 at 15:42
5

Use Thread.sleep(100);. The unit of time is milliseconds

For example:

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}
dominic03
  • 123
  • 8
Bachan Joseph
  • 297
  • 4
  • 5
2

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000) or any other millisecond value:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms) but replace ms with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

meyi
  • 6,235
  • 1
  • 14
  • 26
dominic03
  • 123
  • 8
  • Looking at the almost same answer by @Hecanet there is no `Thread.currentThread().interrupt();` If it is important why is it not shown? - If it is not important why would it be inserted/omitted? – Dirk Schumacher Jul 19 '21 at 06:59
0

There is also one more way to wait.

You can use LockSupport methods, e.g.:

LockSupport.parkNanos(1_000_000_000); // Disables current thread for scheduling at most for 1 second

Fortunately they don't throw any checked exception. But on the other hand according to the documentation there are more reasons for thread to be enabled:

  • Some other thread invokes unpark with the current thread as the target
  • Some other thread interrupts the current thread
Nolequen
  • 2,412
  • 6
  • 33
  • 50