How to sleep a thread in Java

  • 21 July 2016
  • ADM

 

How to sleep a thread in Java - images/logos/java.jpg

 

In Java, if is needed to pause/sleep a thread you can use method Thread.sleep. This is an efficient method of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Two overloaded versions of sleep method are provided:

  • first, that specifies the sleep time to the millisecond;
  • second that specifies the sleep time to the nanosecond. The allowed nanosecond value is between 0 and 999999.

These sleep times are not guaranteed to be precise and are based on the underlying OS. The granularity of sleep is bound by the thread scheduler's interrupt period. The interrupt period for Linux is 1 ms, for Windows, is around 10 or 15 ms. Having this in mind we can conclude that the method with nanoseconds as the parameter will be effective only on an operating system with a lower interrupt period.

Example

package com.admfactory.threads;

public class ThreadsSleep {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Testing Thread.sleep(long millis) - case 1");
        long time0 = System.nanoTime();
        Thread.sleep(3000); // sleep 3 sec
        long time1 = System.nanoTime();
        System.out.println("Expected time 3000000000 nano sec, actual time: " + (time1 - time0) + " nano sec");
        System.out.println();
        System.out.println("Testing Thread.sleep(long millis, int nanos) - case 2");
        long time2 = System.nanoTime();
        Thread.sleep(3000, 500000); // sleep 3.5 sec
        long time3 = System.nanoTime();
        System.out.println("Expected time 3000500000 nano sec, actual time: " + (time3 - time2) + " nano sec");
    }
}

Output

Testing Thread.sleep(long millis) - case 1
Expected time 3000000000 nano sec, actual time: 3000017381 nano sec

Testing Thread.sleep(long millis, int nanos) - case 2
Expected time 3000500000 nano sec, actual time: 3001109697 nano sec

Conclusion

From the output, you can notice that is slightly different the actual time compared with the time we want.