Core Java Concepts and Syntax

Learn about Thread Sleep Method in Java

Learn about Thread Sleep Method in Java

Introduction

The Java Thread.sleep() method allows you to pause a thread's execution for a specified period in milliseconds. Negative values are not allowed for milliseconds. Otherwise, it will throw an IllegalArgumentException.

sleep(long millis, int nanos) is another method for pausing thread execution for a specific time. The values of nanoseconds must fall between 0 and 999999. This article will explore Java's Thread.sleep ().

How Thread.sleep Works

Invoking Thread.sleep() pauses the current Thread by interfacing with its scheduler for a specified time. As soon as the wait time is over, the thread state gets changed to runnable, and it waits for the CPU to execute it.

A thread scheduler, part of the operating system, determines how long the current Thread sleeps.

The syntax for Thread.sleep():

Here is the syntax for Thread.sleep() method.

public static void sleep(long millis)throws InterruptedException
public static void sleep(long millis)throws IllegalArguementException
public static void sleep(long millis, int nanos)throws InterruptedException
public static void sleep(long millis, int nanos)throws  IllegalArguementException

Here,

millis: Thread sleep duration in milliseconds

nanos: Additional duration specified in nanoseconds.

A Few Points to Remember About Sleep()

  • Executing the thread.sleep() methods will result in a halt for the current thread execution.
  • The program throws an InterruptedException exception when another thread interrupts the current thread in sleep mode.
  • As the thread runs on a busy system, its sleeping time is generally longer than its arguments. In contrast, if the system executing sleep() has a lower load, the thread will sleep almost as long as the argument.

Code Sample

import java.io.*;
import java.lang.Thread;

public class Sample {
    public static void main(String[] args) {

        try {
            for (int i = 5; i >= 0; i--) {

                Thread.sleep(1000); // This code will pause the execution for 1 second until loop iterate.
                System.out.println(i);
            }
        } catch (Exception e) {

            System.out.println(e);
        }
    }
}
Output
5
4
3
2
1
0

Negative Sleep Time Throws an IllegalArgumentException

import java.lang.Thread;
import java.io.*;

public class TestSleepMethod3 {
    public static void main(String argvs[]) {
        try {
            for (int x = 0; x < 5; x++) {

                Thread.sleep(-100);

                System.out.println(x);
            }
        } catch (Exception expn) {

            System.out.println(expn);
        }
    }
}


Output

java.lang.IllegalArgumentException: timeout value is negative

write your code here: Coding Playground