Java How to delay few seconds
By:Roy.LiuLast updated:2019-08-17
In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds.
1. TimeUnit
JavaDelayExample.java
package com.mkyong; import java.util.Date; import java.util.concurrent.TimeUnit; public class JavaDelayExample { public static void main(String[] args) { try { System.out.println("Start..." + new Date()); // delay 5 seconds TimeUnit.SECONDS.sleep(5); System.out.println("End..." + new Date()); // delay 0.5 second //TimeUnit.MICROSECONDS.sleep(500); // delay 1 minute //TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { System.err.format("IOException: %s%n", e);
output
Start...Mon Apr 08 21:42:55 SRET 2019 End...Mon Apr 08 21:43:00 SRET 2019
2. Thread.sleep
JavaDelayExample2.java
package com.mkyong; import java.util.Date; public class JavaDelayExample2 { public static void main(String[] args) { try { System.out.println("Start..." + new Date()); // delay 5 seconds Thread.sleep(5000); System.out.println("End..." + new Date()); } catch (InterruptedException e) { System.err.format("IOException: %s%n", e);
From:一号门
Previous:Java How to split a string
COMMENTS