用java编写一个定时器每隔一秒钟,在控制台打印出
时间: 2024-05-12 20:19:12 浏览: 23
当前时间。
```java
import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimerExample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new PrintTimeTask(), 0, 1000);
}
static class PrintTimeTask extends TimerTask {
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()));
}
}
}
```
运行结果如下:
```
2022-02-20 14:08:22
2022-02-20 14:08:23
2022-02-20 14:08:24
2022-02-20 14:08:25
...
```
相关问题
用java 多线程编写一个定时器每隔一秒钟,在控制台打印出
当前时间。
代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimerThread implements Runnable {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000); // 线程休眠1秒钟
Date date = new Date(); // 获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 时间格式化
String time = sdf.format(date); // 格式化时间
System.out.println(time); // 输出时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TimerThread timer = new TimerThread();
Thread thread = new Thread(timer);
thread.start();
}
}
```
代码说明:
1. 定义一个TimerThread类,实现Runnable接口,表示该类是一个线程任务。
2. 在run()方法中,使用while循环,每隔1秒钟执行一次。
3. 获取当前时间,并格式化为字符串,输出到控制台。
4. 在main()方法中,创建一个TimerThread对象,创建一个线程,并启动该线程。
用java 多线程编写一个定时器每隔一秒钟,在控制台打印出当前时间,每行都有注释
```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();
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)