Java 工具类 —— 定时器(Timer/TimerTask)

时间:2022-02-22 03:41:43
import java.util.Timer;
import java.util.TimerTask;

public class Timer {
....
public void schedule(TimerTask task, long delay) {
....
}
....
}

public abstract class TimerTask implements Runnable {
...
}

1. 使用匿名内部类

new Timer().schedule(new TimeTask(){
public void run() {
System.out.println("Time is up.");
System.exit(1);
}
}, 5000);
// 5 秒钟之后执行控制台输出“Time is up”,程序退出;