温馨提示×

java延迟两秒执行怎么实现

小亿
112
2023-12-08 20:45:38
栏目: 编程语言

在Java中,可以使用Thread.sleep()方法来实现延迟执行。Thread.sleep()方法可以将当前线程挂起一段指定的时间,单位为毫秒。

以下是一个简单的示例代码,演示如何延迟两秒执行:

public class DelayExecutionExample {
    public static void main(String[] args) {
        try {
            System.out.println("开始执行");

            // 延迟两秒
            Thread.sleep(2000);

            System.out.println("延迟两秒后执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,通过Thread.sleep(2000)来使当前线程休眠两秒,然后在延迟结束后继续执行后面的代码。

0