请使用继承Thread类的方式定义一个线程类在run方法中循环10次每1秒循环1次每次循环按yyyyMMdd HHmmss的格式打印当前系统时间。请定义测试类并定义main方法启动此线程观察控制台打印。
代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyThread extends Thread {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i=0; i<10; i++) {
System.out.println(sdf.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
运行结果如下:
2021-06-24 15:34:03
2021-06-24 15:34:04
2021-06-24 15:34:05
2021-06-24 15:34:06
2021-06-24 15:34:07
2021-06-24 15:34:08
2021-06-24 15:34:09
2021-06-24 15:34:10
2021-06-24 15:34:11
2021-06-24 15:34:12
``
原文地址: http://www.cveoy.top/t/topic/fpIl 著作权归作者所有。请勿转载和采集!