优化这段代码,使其运行结果只显示一行import java.text.SimpleDateFormat; import java.util.Date; class Timer implements Runnable { public void run() { while(true) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(new Date())); try { Thread.sleep(1000); } catch(InterruptedException e) {e.printStackTrace(); } } } } class Watch { public static void main(String[] args) { Thread thread=new Thread(new Timer()); thread.start(); } }
时间: 2024-02-16 21:59:50 浏览: 82
可以将实例化SimpleDateFormat对象和输出语句移到while循环外,避免每次循环都创建对象,同时使用System.out.print()代替System.out.println(),使输出不换行。代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Date;
class Timer implements Runnable {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void run() {
while (true) {
System.out.print(sdf.format(new Date()) + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Watch {
public static void main(String[] args) {
Thread thread = new Thread(new Timer());
thread.start();
}
}
```
阅读全文