Java –如何延迟几秒钟

在Java中,我们可以使用TimeUnit.SECONDS.sleep()Thread.sleep()延迟几秒钟。

 

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.线程睡眠

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);
        }


    }

}

翻译自: https://mkyong.com/java/java-how-to-delay-few-seconds/
posted @ 2021-01-07 17:40  烧开两锅水  阅读(1740)  评论(0)    收藏  举报