Tuesday, December 12, 2017

How to add delay in your program?

Would like to add delay for a couple of seconds in your program written in Java, then Thread's sleep() method comes to our rescue. It suspends/delays the execution of the current thread for a specified period.

Choose the required method from overloaded version of sleep() method:
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
Note:
  • The sleep time is not guaranteed to be precise, because they are dependent on the facilities provided by the underlying OS.
  • Also, the sleep period can be terminated by interrupts. 
Example: Code snippet showing the use of sleep() method 
package com.anshulsblog;

import java.util.Date;

public class TestSleepMethod {

   public static void main(String[] args) throws InterruptedException {

      System.out.println("Time before calling sleep() method: " + new Date());
      Thread.sleep(5000);  //sleep 5 seconds
      System.out.println("Time after calling sleep() method: " + new Date());
   }
}

Output:
Time before calling sleep() method: Tue Dec 12 10:08:17 IST 2017
Time after calling sleep() method: Tue Dec 12 10:08:22 IST 2017
Look at the main() method, it throws InterruptedException. This is an exception thrown by sleep() method when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException. But one should catch the InterruptedException exception using try catch block.

References:
https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

No comments:

Post a Comment