如何实现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
相关产品推荐
相关产品推荐

