while循环为30秒duration.With在执行我一定要打印当前的日期每5秒......对,我下面写的代码。但它不是按预期工作...
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long duration = (30 * 1000);
do {
while (true) {
try {
System.out.println(" Date: " + new Date());
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} while ((System.currentTimeMillis() - startTime) < duration);
}
其他答案证明了使用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);
无限循环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);
}
我会用一个java.util.Timer
;创建匿名TimerTask
显示Date
6倍于五秒钟,然后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));