Java - 在主方法中使用Thread.sleep

bluesky5月前 ⋅ 133 阅读

ChatGPT的回答仅作参考:

在Java中,可以使用Thread.sleep()方法来使当前线程暂停执行一段时间。在主方法中使用Thread.sleep()方法可以让主线程暂停执行一段时间,以便其他线程有机会执行。

以下是在主方法中使用Thread.sleep()方法的示例代码:

```java
public class Main {
    public static void main(String[] args) {
        System.out.println("Main thread started");

        // Pause the main thread for 5 seconds
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread resumed");
    }
}
```

在上面的代码中,我们在主方法中使用Thread.sleep()方法暂停了主线程5秒钟,然后继续执行。请注意,Thread.sleep()方法可能会抛出InterruptedException异常,因此需要在try-catch块中捕获它。

全部评论: 0

    相关推荐