面试必问!JDK 中定时器是如何实现的?
阅读本文大概需要 6 分钟。
作者:Fooisart
来源:https://www.jianshu.com/p/e21eb60a2c41
jdk中能够实现定时器功能的大致有三种方式:
java.util.Timer
java.util.concurrent.DelayQueue
java.util.concurrent.ScheduledThreadPoolExecutor
一. java.util.Timer
/**
* 安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行
* 每天中午12点都执行一次
*
* @author Fooisart
* Created on 21:46 14-01-2019
*/
public class TimerDemo {
public static void main(String[] args) {
Timer timer = new Timer();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);//控制小时
calendar.set(Calendar.MINUTE, 0);//控制分钟
calendar.set(Calendar.SECOND, 0);//控制秒
Date time = calendar.getTime();//执行任务时间为12:00:00
//每天定时12:00执行操作,每隔2秒执行一次
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(new Date() + "执行任务。。。");
}
}, time, 1000 * 2);
}
}
public void schedule(TimerTask task, Date firstTime, long period) { if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, firstTime.getTime(), -period); }
task 表示要执行的任务逻辑
firstTime 表示第一次执行的时间
period 表示每次间隔时间
private void sched(TimerTask task, long time, long period) { //省略非重点代码 synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } queue.add(task); if (queue.getMin() == task) queue.notify(); } }
给task设定了一些参数,类似于初始化task。这里还给它加了把锁,可以思考一下为甚要在此初始化?为何要加锁?(不是本文范畴,各位伙伴自行思考)
把初始化后的task加入到queue中。
/** * Adds a new task to the priority queue. */ void add(TimerTask task) { // Grow backing store if necessary if (size + 1 == queue.length) queue = Arrays.copyOf(queue, 2*queue.length); queue[++size] = task; fixUp(size); }
public Timer(String name) { thread.setName(name); thread.start(); }
public void run() { try { mainLoop(); } finally { // Someone killed this Thread, behave as if Timer cancelled synchronized(queue) { newTasksMayBeScheduled = false; queue.clear(); // Eliminate obsolete references } } }
/**
* The main timer loop. (See class comment.)
*/
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
//省略
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
if (task.state == TimerTask.CANCELLED) {
queue.removeMin();
continue; // No action required, poll queue again
}
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
if (task.period == 0) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
queue.rescheduleMin(
task.period<0 ? currentTime - task.period
: executionTime + task.period);
}
}
}
if (!taskFired) // Task hasn't yet fired; wait
queue.wait(executionTime - currentTime);
}
if (taskFired) // Task fired; run it, holding no locks
task.run();
} catch(InterruptedException e) {
}
}
}
if (taskFired = (executionTime<=currentTime)),表示已经到了执行时间,那么下面执行任务就好了;
if (!taskFired),表示未到执行时间,那么等待就好了。那么是如何等待的呢?再仔细一看,原来是调用了Object.wait(long timeout)。
java.util.concurrent.DelayQueue
先上示例代码:
public class DelayTask implements Delayed { private Date startDate = new Date(); public DelayTask(Long delayMillions) { this.startDate.setTime(new Date().getTime() + delayMillions); } @Override public int compareTo(Delayed o) { long result = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } @Override public long getDelay(TimeUnit unit) { Date now = new Date(); long diff = startDate.getTime() - now.getTime(); return unit.convert(diff, TimeUnit.MILLISECONDS); }} public static void main(String[] args) throws Exception { BlockingQueue<DelayTask> queue = new DelayQueue<>(); DelayTask delayTask = new DelayTask(1000 * 5L); queue.put(delayTask); while (queue.size()>0){ queue.take(); } }
构造DelayTask,其中的延迟时间是5秒
将任务放入队列
从队列中取任务
public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { E first = q.peek(); if (first == null) available.await(); else { long delay = first.getDelay(NANOSECONDS); if (delay <= 0) return q.poll(); first = null; // don't retain ref while waiting if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
第一次是当队列为空时,等待;
第二次等待是因为,发现有任务,没有到执行时间,并且有准备执行的线程(leader)。咱们得讲理吧,既然已经有人在准备执行了,咱们就得等吧。
第三次是真正延时的地方了,available.awaitNanos(delay),此时也没有别的线程要执行,也就是我将要执行,所有等待剩下的延迟时间即可。
java.util.concurrent.ScheduledThreadPoolExecutor
使用Object.wait()
使用Conditon.await()
使用Thread.sleep()可以实现嘛?如果可以,为何不用呢?
Object.wait()与Conditon.await()有何异同?
<END>
扫码加入技术交流群,不定时「送书」
推荐阅读:
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅