3 回答

TA贡献1829条经验 获得超4个赞
我会用一个java.util.Timer; 创建一个匿名对象TimerTask以在 5 秒内显示Date6 次,然后显示cancel()其本身。这可能看起来像
java.util.Timer t = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask() {
private int count = 0;
@Override
public void run() {
if (count < 6) {
System.out.println(new Date());
} else {
t.cancel();
}
count++;
}
};
t.schedule(task, 0, TimeUnit.SECONDS.toMillis(5));

TA贡献1863条经验 获得超2个赞
无限循环while(true)给你带来了麻烦。
你不需要一个 do-while 循环,除非它是一个特定的要求。
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
long duration = (30 * 1000);
while ((System.currentTimeMillis() - startTime) < duration) {
System.out.println(" Date: " + new Date());
Thread.sleep(5000);
}
}
对于 do-while 循环,您可以重构如下:
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
long duration = (30 * 1000);
do {
System.out.println(" Date: " + new Date());
Thread.sleep(5000);
} while ((System.currentTimeMillis() - startTime) < duration);
}

TA贡献1890条经验 获得超9个赞
其他答案演示了使用while循环和Timer; 这是您可以使用的方法ScheduledExecutorService:
private final static int PERIOD = 5;
private final static int TOTAL = 30;
...
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
System.out.println(new LocalDate());
}, PERIOD, PERIOD, TimeUnit.SECONDS);
executor.schedule(executor::shutdownNow, TOTAL, TimeUnit.SECONDS);
添加回答
举报