You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Date()每秒自动更新?Java定时打印当前时间问题

问题原因

  • Date对象仅在while循环外创建一次,程序运行全程复用同一个固定的时间实例,不会自动更新为最新时间
  • 单次循环包含两次Thread.sleep(1000)和两次打印操作,单次循环总耗时2秒,不符合每秒输出一次的要求
  • 外层无意义的if(true)判断属于冗余代码,不影响运行但无实际作用

修正后代码

public static void main(String[] args) throws InterruptedException{
    OSpanel runner = new OSpanel();
    runner.currentTime();
}

// 移除多余的static修饰符,适配对象调用的写法
public void currentTime() throws InterruptedException{
    while(true) {
        // 每次循环重新获取最新的当前时间
        Date currentTime = new Date();
        System.out.println(currentTime);
        // 打印完成后等待1秒进入下一轮循环
        Thread.sleep(1000);
    }
}

可选调整说明

如果需要保留currentTime方法的static修饰符,可以直接通过类调用静态方法,无需创建对象:

public static void main(String[] args) throws InterruptedException{
    currentTime();
}

public static void currentTime() throws InterruptedException{
    while(true) {
        Date currentTime = new Date();
        System.out.println(currentTime);
        Thread.sleep(1000);
    }
}

内容的提问来源于stack exchange,提问作者Hagelsnow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:00:00