借助Thread,然后让它在while循环里一直运行着,通过sleep方法来控制执行间隔。
public class TimerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
final long timeInterval = 2*1000; // 单位为毫秒
SimpleDateFormat simpleDateFormat =new SimpleDateFormat("HH:mm:ss");//格式化时间
Runnable runnable= new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
System.out.println(simpleDateFormat.format(new Date()) ); //打印当前时间
try {
Thread.sleep(timeInterval); //休眠2秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread thread=new Thread(runnable);
thread.start();
}
}