How to delay code execution in java

We will use  Thread.sleep(miliseconds) to make the current executing Java program to sleep or delay few seconds.

package com.programtalk.learn.java.beginner;

import java.util.Date;

public class DelayForFewSeconds {

	public static void main(String[] args) {

		System.out.println("Started at -> " + new Date());
		try {
			// sleep for 10 seconds as this method takes milliseconnds 10000 ms = 10s
			Thread.sleep(10000);
			System.out.println("After calling sleep -->" + new Date());

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

And the output is :

Started at -> Tue Dec 06 22:39:12 CET 2016
After calling sleep -->Tue Dec 06 22:39:23 CET 2016
Like this post? Don’t forget to share it!

Leave a Reply

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