Sometimes we face the situation where execution of program needs delay or need to stop the program execution for some time. Here are some approaches those perform this delay.
1. Using TimeUnit’s sleep() method
TimeUnit is part of java.util.concurrent.TimeUnit package. TimeUnit is enum class having different units like DAYS,MINUTES,SECONDS and converts the passed value in time unit.
Below example shows how to delay the execution of program by passed value to TimeUnit.SECONDS.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class TimeUnitSleepExecution {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
System.out.println("Execution starts at: " + convertMsToDate(startTime));
try {
//Pause for 5 seconds
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
System.out.println("Exception:" + e.getMessage());
}
//Prints current time after 5 seconds only
long endTime = System.currentTimeMillis();
System.out.println("Execution starts at: " + convertMsToDate(endTime));
}
private static String convertMsToDate(long milliseconds) {
//Creates a simple date format
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
//Create date from milliseconds
Date date = new Date(milliseconds);
//Parse the date using dateFormat
return dateFormat.format(date);
}
}
In above code, TimeUnit.SECONDS.sleep(5) will hold the execution for 5 seconds, next statements will be executed after when execution resumes.
Output:
Execution starts at: 16 Jun 2019 16:13:44
Execution starts at: 16 Jun 2019 16:13:49
2. Using Thread.sleep() method
Second approach of delay execution is Thread.sleep( long millis) method that takes only time in milliseconds.
Below example shows how to delay the execution of program using sleep method of Thread.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadSleepExecution {
public static void main(String[] args) {
try {
System.out.println("Execution starts at: " + convertMsToDate(System.currentTimeMillis()));//statement 1
//Pause for 5 seconds
Thread.sleep(5000);
//Prints current time after 5 seconds only
System.out.println("Execution ends at: " + convertMsToDate(System.currentTimeMillis())); //statement 2
} catch (InterruptedException e) {
System.out.println("Exception:" + e.getMessage());
}
}
private static String convertMsToDate(long milliseconds) {
//Creates a simple date format
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
//Create date from milliseconds
Date date = new Date(milliseconds);
//Parse the date using dateFormat
return dateFormat.format(date);
}
}
In above code, Thread.sleep(5000) will hold the execution for 5 seconds, Statement 2 will be executed after that only when execution resumes.
Execution starts at: 16 Jun 2019 16:15:45
Execution ends at: 16 Jun 2019 16:15:50