Contents

Thread sleep

Writen by: David Vlijmincx

Introduction

In this quick post we look at how to let a thread sleep for a given time.

Sleep

Sleep is used when you want to let a thread wait for a given amount of time. To make a thread sleep, you can use the method Thread.sleep();. It can either take the number of milliseconds, milliseconds and nanoseconds or a Duration as a parameter.

The following example has the MyTask class that implements the Runnable interface. Inside the class is the method run which calls two sleep methods inside a try-catch statement. The first Thread.sleep(1000) call makes the method wait 1000 milliseconds/ 1 second. The second Thread.sleep(Duration.ofSeconds(5)) passes a duration of 5 seconds as a parameter. When waiting on the sleep is done, the application will continue as usual.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class MyTask implements Runnable {

    public void run()
    {
        // Doing some work

        try {
            // wait 1000 milliseconds
            Thread.sleep(1000);

            // wait 5 seconds
            Thread.sleep(Duration.ofSeconds(5));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // continue doing work
    }
}