Java Thread Sleep Example

Sleep method of java.lang.Thread is used to pause current execution of thread for specific period of time.

Some important points about sleep method are :
  • It causes current executing thread to sleep for specific amount of time.
  • Its accuracy depends on system timers and schedulers.
  • It keeps the monitors it has acquired, so if it is called from synchronized context, no other thread can enter that block or method.
  • If we call interrupt() method , it will wake up the sleeping thread.
    synchronized(lockedObject) {   
      Thread.sleep(1000); // It does not release the lock on lockedObject.
      // So either after 1000 miliseconds, current thread will wake up, or after we call 
      //t. interrupt() method.
      
  
Example: Create a class FirstThread.java as below.
package org.arpit.java2blog.thread;

public class FirstThread implements Runnable{

 public void run()
 {
  System.out.println("Thread is running");
 }
 
}
Create main class named ThreadSleepExampleMain.java
package org.arpit.java2blog.thread;

public class ThreadSleepExampleMain {
 
 public static void main(String args[])
 {
  FirstThread ft= new FirstThread();
  
  Thread t=new Thread(ft);
  t.start();
  long startTime=System.currentTimeMillis();
  try {
                // putting thread on sleep
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  long endTime=System.currentTimeMillis();
  long timeDifference=(endTime-startTime);
  System.out.println("Time difference between before and after sleep call: "+timeDifference);
 }

}

When you run above program, you will get following output.
Thread is running
Time difference between before and after sleep call: 1001
You can see there is delay of 1 milliseconds. As mentioned earlier,its accuracy depends on system timers and schedulers.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012