用java 多线程编写一个定时器每隔一秒钟,在控制台打印出当前时间,每行都有注释
时间: 2024-05-08 17:15:16 浏览: 167
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimerThread extends Thread {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void run() {
while (true) { // 循环执行
try {
// 获取当前时间
Calendar calendar = Calendar.getInstance();
String currentTime = sdf.format(calendar.getTime());
System.out.println(currentTime); // 打印当前时间
Thread.sleep(1000); // 线程休眠1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TimerThread timerThread = new TimerThread();
timerThread.start();
}
}
```
阅读全文