JAVA var namelist=[ "张三","李四","王五","贺六","孙九","赵十","刘一 将这些人名依次每隔2秒输出一个名字
时间: 2023-12-21 21:32:10 浏览: 56
姓名.java
以下是使用Java实现每隔2秒输出人名的代码示例:
```java
import java.util.Timer;
import java.util.TimerTask;
public class NamePrinter {
private static String[] namelist = {"张三", "李四", "王五", "贺六", "孙九", "赵十", "刘一"};
public static void main(String[] args) {
Timer timer = new Timer();
int delay = 0; // 初始延迟为0秒
int period = 2000; // 每隔2秒执行一次
timer.scheduleAtFixedRate(new TimerTask() {
int index = 0;
public void run() {
if (index < namelist.length) {
System.out.println(namelist[index]);
index++;
} else {
timer.cancel(); // 所有名字输出完毕后取消定时器
}
}
}, delay, period);
}
}
```
阅读全文