Java 定时任务的几种实现方式总结

2025-05-09 01:54:35
推荐回答(1个)
回答1:

实现一、使用Thread等待的方式
public static class TimerThread extends Thread{
@Override
public void run() {
super.run();
while (true){
doSomething();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void doSomething() {
}
}
实现二、timer的方式
static {
Timer timer = new Timer();
//一秒后执行,没五秒执行一次
timer.schedule(new ImpTwoTimerTask(),1000,5000);
}
public static class ImpTwoTimerTask extends TimerTask {
@Override
public void run() {
doSomething();
}
}