【问题标题】:Print current date every 5 sec with in a 30 sec loop在 30 秒循环中每 5 秒打印一次当前日期
【发布时间】:2019-02-11 04:57:43
【问题描述】:

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

}

【问题讨论】:

  • 我没有看到打破内部while (true)循环的条件
  • 你认为内循环的执行应该如何结束?如果要每 5 秒打印一次,为什么要在内循环中休眠 2 秒?
  • @divz 我看不出你想在这里实现什么。

标签: java


【解决方案1】:

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

【讨论】:

    【解决方案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);
    }
    

    【讨论】:

    • 我真正的要求是在 do while 循环中,我必须在 30 秒内获得一些服务器响应......在此期间每 5 秒我必须发送一些按键......如何我可以使用上面的代码执行此操作吗?
    • 在这种情况下,Thread.sleep(); 可能会很棘手。您可以按照@elliott-frisch 或java.util.concurrent.CountDownLatch 的建议使用java.util.Timerawait()
    • 但是我可以把获取服务器响应的代码放在哪里?
    【解决方案3】:

    我会使用java.util.Timer;创建一个匿名 TimerTask 以在 5 秒内显示 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));
    

    【讨论】:

    • 我真正的要求是在 do while 循环中,我必须在 30 秒内获得一些服务器响应......在此期间每 5 秒我必须发送一些按键......如何我可以使用上面的代码执行此操作吗?我试过但有点困惑将“获取服务器响应代码”放在哪里
    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多