为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2022-06-15 09:35:22
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 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

我会用一个java.util.Timer; 创建一个匿名对象TimerTask以在 5 秒内显示Date6 次,然后显示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));


查看完整回答
反对 回复 2022-06-15
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

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

}


查看完整回答
反对 回复 2022-06-15
?
当年话下

TA贡献1890条经验 获得超9个赞

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


查看完整回答
反对 回复 2022-06-15
  • 3 回答
  • 0 关注
  • 175 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号