schedule与scheduleAtFixedRate之Timer源码分析
执行Timer任务调度方法有如下几种:

这些方法最后调用的都是这个方法:
private void sched(TimerTask task, long time, long period)
private void sched(TimerTask task, long time, long period) {
if (time < 0)
throw new IllegalArgumentException("Illegal execution time.");
// Constrain value of period sufficiently to prevent numeric
// overflow while still being effectively infinitely large.
if (Math.abs(period) > (Long.MAX_VALUE >> 1))
period >>= 1;
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();
}
}
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) {
// Wait for queue to become non-empty,等待被notify激活
while (queue.isEmpty() && newTasksMayBeScheduled)
queue.wait();
if (queue.isEmpty())
break; // Queue is empty and will forever remain; die
// Queue nonempty; look at first evt and do the right thing
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) { // 如果period=0,则任务进行一次便结束,并移出队列
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // 设置下一次执行的时间
// task.period<0 对应 scheduleAtFixedRate 方法
// task.period>0 对应 schedule 方法
queue.rescheduleMin(
task.period<0 ? currentTime - task.period
: executionTime + task.period);
}
}
}
// 任务执行时间没到,等待,直到下一次执行时间大于当前时间
if (!taskFired)
queue.wait(executionTime - currentTime);
}
// 执行任务时间到达,开始执行任务,没有加锁,并发执行
if (taskFired) // Task fired; run it, holding no locks
task.run();
} catch(InterruptedException e) {
}
}
}
schedule与scheduleAtFixedRate之Timer源码分析的更多相关文章
- Unity时钟定时器插件——Vision Timer源码分析之二
Unity时钟定时器插件——Vision Timer源码分析之二 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com 前面的已经介绍了vp_T ...
- 并发编程 —— Timer 源码分析
前言 在平时的开发中,肯定需要使用定时任务,而 Java 1.3 版本提供了一个 java.util.Timer 定时任务类.今天一起来看看这个类. 1.API 介绍 Timer 相关的有 3 个类: ...
- Java并发编程笔记之Timer源码分析
timer在JDK里面,是很早的一个API了.具有延时的,并具有周期性的任务,在newScheduledThreadPool出来之前我们一般会用Timer和TimerTask来做,但是Timer存在一 ...
- Unity时钟定时器插件——Vision Timer源码分析之一
因为项目中,UI的所有模块都没有MonBehaviour类(纯粹的C#类),只有像NGUI的基本组件的类是继承MonoBehaviour.因为没有继承MonoBehaviour,这也不能使用Updat ...
- storm定时器timer源码分析-timer.clj
storm定时器与java.util.Timer定时器比较相似.java.util.Timer定时器实际上是个线程,定时调度所拥有的TimerTasks:storm定时器也有一个线程负责调度所拥有的& ...
- JUC源码分析-线程池篇(三)Timer
JUC源码分析-线程池篇(三)Timer Timer 是 java.util 包提供的一个定时任务调度器,在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次. 1. Ti ...
- Nimbus<二>storm启动nimbus源码分析-nimbus.clj
nimbus是storm集群的"控制器",是storm集群的重要组成部分.我们可以通用执行bin/storm nimbus >/dev/null 2>&1 &a ...
- python线程threading.Timer源码解读
threading.Timer的作用 官方给的定义是: """Call a function after a specified number of seconds: t ...
- [源码分析] 并行分布式任务队列 Celery 之 Timer & Heartbeat
[源码分析] 并行分布式任务队列 Celery 之 Timer & Heartbeat 目录 [源码分析] 并行分布式任务队列 Celery 之 Timer & Heartbeat 0 ...
随机推荐
- Maven使用中的常见问题整理
1.更新eclipse的classpath加入新依赖 1.在dependencyManagement里面加入包括版本在内的依赖信息,如: <dependency> <groupId ...
- Java 设计模式之工厂模式(二)
原文地址:Java 设计模式之工厂模式(二) 博客地址:http://www.extlight.com 一.背景 本篇内容是 Java 设计模式创建型模式的第二篇.上一篇主题为 <Java 设计 ...
- Shell脚本一键安装LNMP环境
https://sourceforge.net/projects/opensourcefile/files/ Nginx是一款高性能的HTTP和反向代理服务器.Nginx在反向代理,Rewrite规则 ...
- maven打包报错:在类路径或引导类路径中找不到程序包 java.lang
刚下了个新项目,跑了下maven报错了: E:\workspace\portalframe>mvn clean install [INFO] Scanning for projects... [ ...
- Python一些特殊用法(map、reduce、filter、lambda、列表推导式等)
Map函数: 原型:map(function, sequence),作用是将一个列表映射到另一个列表, 使用方法: def f(x): return x**2 l = range(1,10) map( ...
- WebApi FormData+文件长传 异步+同步实现
// POST api/values public async Task Post() { try { // 检查该请求是否含有multipart/form-data if (!Request.Con ...
- SAX解析类:SaxHelper
public class SaxHelper extends DefaultHandler { private Person person; private ArrayList<Person&g ...
- ActiveMQ之一--ActiveMQ入门
MQ的消费-生产者模型的一个典型的代表,一端往消息队列中不断的写入消息,而另一端则可以读取或者订阅队列中的消息.MQ和JMS类似,但不同的是JMS是SUN JAVA消息中间件服务的一个标准和API定义 ...
- JSR-303 结合spring 校验
使用注解 一.准备校验时使用的JAR validation-api-1.0.0.GA.jar:JDK的接口: hibernate-validator-4.2.0.Final.jar是对上述接口的实现: ...
- C++获取本机的ip地址程序
#include <WinSock2.h> #pragma comment(lib,"ws2_32") //链接到ws2_32动态链接库 class CInitSock ...