java实现程序等待一段时间(附完整源码)
时间: 2023-12-17 17:05:46 浏览: 25
可以使用Thread.sleep()方法让程序等待一段时间,该方法需要传入等待的毫秒数作为参数。以下是Java实现程序等待一段时间的完整源码示例:
```java
public class WaitTime {
public static void main(String[] args) {
System.out.println("程序开始执行...");
try {
Thread.sleep(5000); // 等待5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("程序执行完毕。");
}
}
```
在上述示例中,程序会等待5秒后才输出“程序执行完毕。”的信息。使用try-catch块捕获InterruptedException异常,以防线程在等待期间被中断。
相关问题
java实现关机程序(附完整源码)
下面是一个简单的Java实现关机程序的示例代码:
```java
import java.io.IOException;
public class ShutdownProgram {
public static void main(String[] args) throws IOException {
// 使用Runtime类的exec()方法执行命令
Runtime.getRuntime().exec("shutdown -s -t 60");
// -s参数表示关机,-t参数表示延迟时间,单位为秒
// 这里的命令表示在60秒后关机
// 输出提示信息
System.out.println("计算机将在60秒后关机!");
}
}
```
在这个例子中,我们使用了 Java 的 Runtime 类的 exec() 方法来执行命令,实现计算机的关机操作。具体而言,我们使用了 shutdown 命令,并传入了相应的参数:-s 表示关机,-t 表示延迟时间,单位为秒。最后,我们输出了一条提示信息,告诉用户计算机将在多少秒后关机。需要注意的是,这个程序需要在管理员权限下运行才能够正常执行。
java实现暂停程序(附完整源码)
以下是一个简单的 Java 程序,可以通过输入 "pause" 暂停程序,输入 "resume" 恢复程序运行。
```java
import java.util.Scanner;
public class PauseProgram {
private static boolean isPaused = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
if (!isPaused) {
System.out.println("Program is running!");
}
String input = scanner.nextLine();
if (input.equals("pause")) {
isPaused = true;
System.out.println("Program paused.");
} else if (input.equals("resume")) {
isPaused = false;
System.out.println("Program resumed.");
}
}
}
}
```
在这个程序中,我们使用了一个静态变量 `isPaused` 来跟踪程序是否被暂停。在主循环中,如果程序没有被暂停,就输出一条消息告诉用户程序正在运行。然后,我们读取用户的输入,如果输入是 "pause",就将 `isPaused` 设置为 `true`,表示程序被暂停。如果输入是 "resume",就将 `isPaused` 设置为 `false`,表示程序恢复运行。
注意,这个程序只是一个简单的示例,实际应用中可能需要更复杂的逻辑来暂停和恢复程序运行。