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

问题描述 投票:-2回答:3

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

}
java
3个回答
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
投票

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

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));
© www.soinside.com 2019 - 2024. All rights reserved.