JDK Timer
Timer timer = new Timer();
timer.schedule(new java.util.TimerTask() {
@Override
public void run() {
System.out.println("ATask 3s 后执行");
}
}, 3000);
timer.schedule(new java.util.TimerTask() {
@Override
public void run() {
System.out.println("BTask 5s 后执行");
}
}, 5000);
定时任务线程池
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
scheduledExecutorService.schedule(() -> {
System.out.println("ATask 3s 后执行");
}, 3, TimeUnit.SECONDS);
scheduledExecutorService.schedule(() -> {
System.out.println("BTask 5s 后执行");
}, 5, TimeUnit.SECONDS);
时间轮
HashedWheelTimer hashedWheelTimer=new HashedWheelTimer();
hashedWheelTimer.start();
hashedWheelTimer.newTimeout(new ATimerTask(),3, TimeUnit.SECONDS);
hashedWheelTimer.newTimeout(new BTimerTask(),5,TimeUnit.SECONDS);
详细
算法比较 使用场景