日历秒数在 while 循环中没有增加

我试图让 while 循环在 5 秒半 (5.5) 后停止,所以我使用 Calendar 库获取分钟的当前秒数,然后将 5.5 递增到它上面。在该过程之后,它循环等待当前时间等于保存的变量


我意识到秒数没有增加……这是为什么?


代码:


package me.fangs.td;


import java.util.Calendar;


public class Main {

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();

        double timeout = calendar.get(Calendar.SECOND) + 5.5;

        while((double) calendar.get(Calendar.SECOND) < timeout) {

            System.out.println((double) calendar.get(Calendar.SECOND));

            Thread.sleep(1000);

        }

    }

}


海绵宝宝撒
浏览 87回答 3
3回答

慕容森

我根本不会使用 Calender 库,而是使用System.currentTimeMillis()这是一个在 5.5 秒后终止的 while 循环:long end = System.currentTimeMillis() + 5500;while (System.currentTimeMillis() < end) {&nbsp; //Do something}//Exit after 5.5 seconds这个版本的优点是,您可以在循环运行时更改结束时间,从而更改循环运行的时间。

胡说叔叔

与其实现我自己的,我更喜欢/使用Timer它是一种线程工具,可以在后台线程中安排任务以供将来执行。像,Timer t = new Timer();TimerTask task = new TimerTask() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Five seconds");&nbsp; &nbsp; }};t.schedule(task, TimeUnit.SECONDS.toMillis(5) + 500); // 5.5 seconds.

慕标琳琳

java.timeVoroX的回答是正确的。但是使用 java.time 使它更加优雅和自我记录。我们通过循环调用Instant.now每次以捕获新的当前时间。日期时间对象不会自动更新。它们是那一刻的快照,冻结了。在每种情况下询问您何时需要当前时间。Duration wait = Duration.ofSeconds( 5 ).plusMillis( 500 ) ;&nbsp; // 5.5 seconds.Instant now = Instant.now() ;Instant stop = now.plus( d ) ;while( Instant.now().isBefore( stop ) )&nbsp;{&nbsp; &nbsp;// Do some task.&nbsp;}&nbsp;在实际工作中,我还会添加一个检查,stop.isAfter( start )以防 Duration 被编辑为负值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java