java编写程序,要求每隔一秒获取一次当前时间
时间: 2024-02-18 18:35:32 浏览: 48
可以使用Java中的Timer类,每隔一秒执行一次获取当前时间的操作:
```java
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Date now = new Date();
System.out.println(now);
}
}, 0, 1000); // 第二个参数表示延迟时间,第三个参数表示间隔时间
```
这样就可以每隔一秒打印一次当前时间了。
相关问题
用java编写一个定时器每隔一秒钟,在控制台打印出
当前时间。
```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对象,创建一个线程,并启动该线程。