• notice
  • Congratulations on the launch of the Sought Tech site

How to make the program wait for a period of time in JAVA

  In JAVA, if you want the code to wait for a period of time before continuing to execute, you can let the current thread sleep for a period of time.


Method 1: Through the sleep method of the thread.

1 Thread.currentThread().sleep(1000);

  Add this statement where the program needs to wait to make the program wait. The parameter 1000 here is in milliseconds, that is, this statement can make the program wait for 1 second.


Method 2: The sleep method in the TimeUnit class.

TimeUnit.DAYS.sleep(1); // day
TimeUnit.HOURS.sleep(1); // hour
TimeUnit.MINUTES.sleep(1); // minute
TimeUnit.SECONDS.sleep(1); // seconds
TimeUnit.MILLISECONDS.sleep(1000); // milliseconds
TimeUnit.MICROSECONDS.sleep(1000); // microseconds
TimeUnit.NANOSECONDS.sleep(1000); // nanoseconds

 The method provided by the TimeUnit class actually calls the sleep method of the Thread class at the bottom layer, allowing the program to wait. It's just that he encapsulates it according to the time unit at the upper level. As shown in the figure above, there are 7 types to choose from, and you can easily choose the time unit you need to use.


Technical otaku

Sought technology together

Related Topic


Leave a Reply