Java 以30秒循环,每5秒打印一次当前日期

Java 以30秒循环,每5秒打印一次当前日期,java,Java,do while循环将执行30秒。因为我必须每5秒打印一次当前日期。。。为此,我编写了如下代码。但它并没有像预期的那样工作 public static void main(String[] args) { long startTime = System.currentTimeMillis(); long duration = (30 * 1000); do { while (true) {

do while循环将执行30秒。因为我必须每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);

}
publicstaticvoidmain(字符串[]args){
long startTime=System.currentTimeMillis();
长持续时间=(30*1000);
做{
虽然(正确){
试一试{
System.out.println(“日期:+新日期());
线程。睡眠(2*1000);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}while((System.currentTimeMillis()-startTime)<持续时间);
}
无限循环
,而(true)
会给您带来麻烦

除非是特定的需求,否则您不需要执行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);
    }
}
publicstaticvoidmain(String[]args)抛出InterruptedException{
long startTime=System.currentTimeMillis();
长持续时间=(30*1000);
while((System.currentTimeMillis()-startTime)<持续时间){
System.out.println(“日期:+新日期());
睡眠(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);
}
publicstaticvoidmain(String[]args)抛出InterruptedException{
long startTime=System.currentTimeMillis();
长持续时间=(30*1000);
做{
System.out.println(“日期:+新日期());
睡眠(5000);
}while((System.currentTimeMillis()-startTime)<持续时间);
}

我会使用
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));
java.util.Timer t=new java.util.Timer();
java.util.TimerTask=new java.util.TimerTask(){
私有整数计数=0;
@凌驾
公开募捐{
如果(计数<6){
System.out.println(新日期());
}否则{
t、 取消();
}
计数++;
}
};
t、 时间表(任务,0,时间单位。秒。托米利斯(5));

其他答案演示了如何使用
循环和
计时器执行此操作;以下是如何使用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);

我看不到一个打破内部循环的条件,而(true)
内部循环的执行应该如何结束?如果你想每5秒打印一次,为什么你要在内部循环中睡2秒?@divz我不知道你想在这里实现什么。可能的重复:我真正的要求是在do-while循环中,我必须在30秒内得到一些服务器响应……在这期间,每5秒我必须发送一些按键……我如何执行这是使用上述代码实现的吗?在这种情况下,
Thread.sleep()可能很棘手。您可以使用@elliott frisch建议的
java.util.Timer
java.util.concurrent.CountDownLatch
await()
但是我可以将获取服务器响应的代码放在哪里?我真正的要求是在do-while循环中,我必须在30秒内获取一些服务器响应……在这段时间之间,每5秒我必须发送一些按键……我如何使用上述代码执行此操作?我尝试过,但有点困惑“获取服务器响应代码”应该放在哪里