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:
Note:
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
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
- 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.
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
References:
https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
No comments:
Post a Comment