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

Calendar seconds are not increasing in while loop

我试图让 while 循环在 5 秒半 (5.5) 后停止,所以我使用日历库获取当前的秒数,然后将 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);
        }
    }
}

我更喜欢/使用 Timer,而不是自己实现,这是 线程安排任务以在后台线程中执行的工具。 比如,

Timer t = new Timer();
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        System.out.println("Five seconds");
    }
};
t.schedule(task, TimeUnit.SECONDS.toMillis(5) + 500); // 5.5 seconds.

我根本不会使用日历库,而是使用 System.currentTimeMillis()

这是一个在 5.5 秒后终止的 while 循环:

long end = System.currentTimeMillis() + 5500;
while (System.currentTimeMillis() < end) {
  //Do something
}
//Exit after 5.5 seconds

此版本的优点是,您可以在循环 运行ning 时更改结束时间,更改循环的时间将 运行。

java.time

是正确的。但是使用 java.time 使它更优雅并且 self-documenting。

我们每次通过循环调用Instant.now来捕获新的当前时间。 date-time 对象不是 auto-updating。它们是那一刻的快照,冻结了。在每种情况下询问您何时需要当前时间。

Duration wait = Duration.ofSeconds( 5 ).plusMillis( 500 ) ;  // 5.5 seconds.
Instant now = Instant.now() ;
Instant stop = now.plus( d ) ;

while( Instant.now().isBefore( stop ) ) 
{
   // Do some task. 
} 

在实际工作中,我还会添加一个检查 stop.isAfter( start ) 以防 Duration 被编辑为负值。