How to Make Java Delay Few Seconds


In this example, we will learn two methods to make the current executing java program delay few seconds.

Source Code

1) Using Thread.sleep()

package com.beginner.examples;

import java.util.Date;

public class DelayExample1 {

    public static void main(String[] args) {

    	System.out.println("It is : " + new Date());		
		try 
		{
			Thread.sleep(3000);
			System.out.println("It is : " + new Date());
			
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
    }
}

Output:

It is : Sun Mar 03 12:06:15 UTC 2019
It is : Sun Mar 03 12:06:18 UTC 2019

2) Using TimeUnit.SECONDS.sleep()

package com.beginner.examples;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DelayExample2 {

    public static void main(String[] args) {

    	System.out.println("It is : " + new Date());		
		try 
		{
			TimeUnit.SECONDS.sleep(3);
			System.out.println("It is : " + new Date());
			
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
    }
}

Output:

It is : Sun Mar 03 12:06:15 UTC 2019
It is : Sun Mar 03 12:06:18 UTC 2019

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments