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

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


}


ITMISS
浏览 176回答 3
3回答

浮云间

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

小唯快跑啊

无限循环while(true)给你带来了麻烦。你不需要一个 do-while 循环,除非它是一个特定的要求。public static void main(String[] args) throws InterruptedException {&nbsp; &nbsp; long startTime = System.currentTimeMillis();&nbsp; &nbsp; long duration = (30 * 1000);&nbsp; &nbsp; while ((System.currentTimeMillis() - startTime) < duration) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" Date: " + new Date());&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(5000);&nbsp; &nbsp; }}对于 do-while 循环,您可以重构如下:public static void main(String[] args) throws InterruptedException {&nbsp; &nbsp; long startTime = System.currentTimeMillis();&nbsp; &nbsp; long duration = (30 * 1000);&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" Date: " + new Date());&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(5000);&nbsp; &nbsp; } 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(() -> {&nbsp; &nbsp; System.out.println(new LocalDate());}, PERIOD, PERIOD, TimeUnit.SECONDS);executor.schedule(executor::shutdownNow, TOTAL, TimeUnit.SECONDS);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java