Tutorial

Thread.sleep() in Java - Java Thread sleep

Updated on November 23, 2022
authorauthor

Pankaj and Bradley Kouchi

Thread.sleep() in Java - Java Thread sleep

Introduction

The Java Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds. The argument value for milliseconds cannot be negative. Otherwise, it throws IllegalArgumentException.

sleep(long millis, int nanos) is another method that can be used to pause the execution of the current thread for a specified number of milliseconds and nanoseconds. The allowed nanosecond values are between 0 and 999999.

In this article, you will learn about Java’s Thread.sleep().

How Thread.sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in a wait state for a specified period of time. Once the wait time is over, the thread state is changed to a runnable state and waits for the CPU for further execution. The actual time that the current thread sleeps depends on the thread scheduler that is part of the operating system.

Java Thread.sleep important points

  1. It always pauses the current thread execution.
  2. The actual time the thread sleeps before waking up and starting execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time, but for a busy system, it will be a little bit longer.
  3. Thread.sleep() doesn’t lose any monitors or lock the current thread it has acquired.
  4. Any other thread can interrupt the current thread in sleep, and in such cases InterruptedException is thrown.

Java Thread.sleep Example

Here is an example program where Thread.sleep() is used to pause the main thread execution for 2 seconds (2000 milliseconds):

ThreadSleep.java
package com.journaldev.threads;

public class ThreadSleep {

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();

        Thread.sleep(2000);

        System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start));
    }
}

First, this code stores the current system time in milliseconds. Then it sleeps for 2000 milliseconds. Finally, this code prints out the new current system time minus the previous current system time:

Output
Sleep time in ms = 2005

Notice that this difference is not precisely 2000 milliseconds. This is due to how Thread.sleep() works and the operating system-specific implementation of the thread scheduler.

Conclusion

In this article, you learned about Java’s Thread.sleep().

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 30, 2013

Thanks for short and useful post on Thread.sleep() method. I think 2000 is meant, and not 200, here: “If you will run the above program, you will notice that the sleep time it prints is slightly greater than 200 and caused by …” in this post. Please amend this.

- Rishi Raj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 12, 2014

Thanku for short and useful notes on thread.sleep()…

- Balwant

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 26, 2015

    hi sir just one question, once the thread is in sleep mode how can it be interrupted? You have mentioned this in 4 point as “Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.” thanks ashish

    - Ashish

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 11, 2016

    How to check whether thread is sleeping mode or not?

    - Sundara Baskaran

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 20, 2016

      class TestCallRun extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{Thread.sleep(5000);}catch(InterruptedException e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ TestCallRun2 t1=new TestCallRun2(); TestCallRun2 t2=new TestCallRun2(); t1.start(); t2.run(); } } why the output of above program is same as when we call t1.start(); t2.start(). 1 1 2 2 3 3 4 4 but output is different when we call t1.run();t2.run(); 1 2 3 4 1 2 3 4 according to my understating output of t1.start(); t2.run() should be 1 --t1 thread 1 --t2 thread 2 --t2 thread 3 --t2 thread 4 --t2 thread 2 --t1 thread 3 --t1 thread 4 --t1 thread

      - Nitin

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 11, 2016

      Hi Pankaj, Your blog is very good and more informative. But its very good if you provide link to export to pdf. Thanks Maruthi

      - maruthi

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 7, 2017

        Hi Pankaj, I modified your code like below, and I can see same sleep time after every execution – long sleepTime = 999; System.out.println("Going to sleep for "+sleepTime); long start = 0L; try { start = System.currentTimeMillis(); Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start)); I guess, the difference is coming due to the startTime capture statement execution and the actual sleep statement, if you keep them one after the other, you won’t see the difference anymore. I understand that your explanation is correct too, because all thread execution depends on how OS allow them. Thanks

        - Punit

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 2, 2017

        Thread One = new Thread( ()-> {}); What is the difference between calling One.sleep() and Thread.sleep();

        - James

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 28, 2018

        long start = System.currentTimeMillis(); what does this line have in the code?

        - FREDY ORLANDO MARCELO CASTIBLANCO

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 3, 2019

        Suppose if a thread is kept in sleep and after completing sleep mode time the processor is running another thread. then will the current thread stops and executes thread that completed sleep mode or thread that is in sleep mode executed after current running process is terminated please explain it in detail I am new to java

        - Pavan

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.