1.并发包
public static void main(String[] args) {
Runnable runnable = new Runnable() {
int i = 1;
@Override
public void run() {
System.out.println("执行次数:第"+ i++ +"次");
System.out.println("---定时器执行---");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable,0,2000, TimeUnit.MILLISECONDS);
}
2.TimerTask
在这里插入代码片
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("----定时器开始执行---");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeroiod = 5*1000;
timer.scheduleAtFixedRate(task,delay,intevalPeroiod);
}