How do I make a delay in Java?

前端 未结 8 1407
Happy的楠姐
Happy的楠姐 2020-11-22 08:24

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

while (true) {
    if (i == 3) {
        i         


        
8条回答
  •  忘了有多久
    2020-11-22 09:09

    Use Thread.sleep(100);. The unit of time is milliseconds

    For example:

    public class SleepMessages {
        public static void main(String args[])
            throws InterruptedException {
            String importantInfo[] = {
                "Mares eat oats",
                "Does eat oats",
                "Little lambs eat ivy",
                "A kid will eat ivy too"
            };
    
            for (int i = 0;
                 i < importantInfo.length;
                 i++) {
                //Pause for 4 seconds
                Thread.sleep(4000);
                //Print a message
                System.out.println(importantInfo[i]);
            }
        }
    }
    

提交回复
热议问题