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

时间:2019-02-11 04:57:44

标签: java

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);

}

3 个答案:

答案 0 :(得分:2)

其他答案证明了使用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);

答案 1 :(得分:1)

无限循环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);
}

答案 2 :(得分:1)

我会使用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));
相关问题