Thread.sleep() in Java – Java Thread sleep

Filed Under: Java

Thread.sleep in Java

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

java thread sleep, Thread.sleep in java

There is another overloaded method sleep(long millis, int nanos) that can be used to pause the execution of current thread for specified milliseconds and nanoseconds. The allowed nano second value is between 0 and 999999.

Java Thread Sleep Example

Here is a simple program where Thread.sleep() is used to pause the main thread execution for 2 seconds.

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));
        
    }

}

If you will run the above program, you will notice that the thread sleep time it prints is slightly greater than 2000. This is caused by how thread sleep works and operating system specific implementation of thread scheduler.

Java Thread Sleep important points

  1. It always pause the current thread execution.
  2. The actual time thread sleeps before waking up and start 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 little bit more.
  3. Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  4. Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

How Thread Sleep Works

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

Comments

  1. Ishant says:

    how do we come to know that, how much time we have to provide to the threads for sleep or wait.

    If we are working on big projects.

  2. Pavan says:

    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

  3. FREDY ORLANDO MARCELO CASTIBLANCO says:

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

    1. lily says:

      i think that

    2. Praveen E says:

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

      We are measuring current time minus time before we are putting the thread to sleep. So, we are checking how much time did the thread actually slept

  4. James says:

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

    1. Bala says:

      sleep is a static method hence we can call using instance as well, it will have same effect as calling Thread.sleep(). Recommended way to use static methods is using class name instead of instances.

  5. Punit says:

    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

    1. Banjamin says:

      Hi,
      I’m noticed your post.In your code,the result is same what you have said,I guess the reason for you got this result is you didn’t get the current time more precisely.Because CPU is very fast ,only you can see the difference when you use the System.nanoTime() to get the current time.Then you will see the print time is greater than the sleep time in nano second level.
      Let me know if you have any question about my answer.
      hope that helps.

  6. maruthi says:

    Hi Pankaj,

    Your blog is very good and more informative. But its very good if you provide link to export to pdf.

    Thanks
    Maruthi

  7. Nitin says:

    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

    1. Vikas says:

      Although output of multi-threaded program depends on JVM, in this case output is correct.
      when you are using t1.start() and t2start() there are total of three threads in execution
      t1
      t2 and
      main
      main completes its execution without printing anything.
      whereas t1 and t2 take turns, when of them is put to sleep other one kicks and complete some part of its execution.

      In second case there are two threads of execution one is t1 and other is main
      now t2.run is just a method in main which puts the current thread i.e., main to sleep and let t1 take turn.

      That’s the reason of your answer.

      If you want to observe this:

      create named threads and print their name along with integers in output.

  8. Sundara Baskaran says:

    How to check whether thread is sleeping mode or not?

  9. Ashish says:

    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

    1. Mohammed Manna says:

      All sleep does is that it puts the thread into a “State” where it’s execution is “Suspended” i.e. it’s waiting. But it is still very much functional and has a “Waiting” state. The thread is also very much “Alive”. In this state, if you interrupt this thread, you are actually interrupting it’s current state i.e. “Waiting” state. From there, it will do the duties set within the “catch” block for InterruptedException being caught in the run() method.

      1. Sanjay says:

        still i didn’t get the answer for the question “once the thread is in sleep mode how can it be interrupted?”

        1. Sujit Lole says:

          package com.org.multithreading.sleep;

          public class SleepInterupt {
          public static void main(String[] args) throws InterruptedException {
          Thread t = new InterruptDemo();
          t.start();
          t.interrupt();

          }
          }

          class InterruptDemo extends Thread {

          public void run() {
          System.out.println(“Thread started….”);
          try {
          Thread.sleep(2000);
          } catch (InterruptedException e) {
          e.printStackTrace();
          }

          System.out.println(“Thread stopped….”);
          }
          }

  10. Balwant says:

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

  11. Rishi Raj says:

    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.

    1. Rishi Raj says:

      Please respond to my comment. It concerns readers.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages