java提供了方便的定时器功能,代码示例:

public class ScheduledThreadPool_Test {
static class Command implements Runnable {
@Override
public void run() {
System.out.println("zhang");
}
} public static void main(String[] args) throws IOException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
pool.scheduleWithFixedDelay(new Command(), 1000, 5000, TimeUnit.MILLISECONDS);
System.in.read();
}
}

接下来分析ScheduledThreadPoolExecutor:

// 省略其他代码
public class Executors {
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
} public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService { public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
} public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (delay <= 0)
throw new IllegalArgumentException();
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(-delay));
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
//把任务添加到队列中,创建工作线程
delayedExecute(t);
return t;
}
}

调用scheduleWithFixedDelay方法,把任务添加到DelayedWorkQueue,并启动工作线程。

private void delayedExecute(RunnableScheduledFuture<?> task) {
if (isShutdown())
reject(task);
else {
//把任务添加到队列
super.getQueue().add(task);
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
ensurePrestart(); // 创建线程
}
}

从队列中取任务的调用栈:

任务在执行的时候,会新建一个任务,放入队列中,这样就实现了定时任务的功能。

从上面能看出:定时的功能主要是由DelayedWorkQueue和ScheduledFutureTask保证的。

DelayedWorkQueue的底层数据结构是由数组实现的堆(堆是一棵完全二叉树,以小顶堆为例,parent节点值小于左右孩子节点的值):

// 省略其他代码
static class DelayedWorkQueue extends AbstractQueue<Runnable>
implements BlockingQueue<Runnable> {
private static final int INITIAL_CAPACITY = 16;
private RunnableScheduledFuture[] queue =
new RunnableScheduledFuture[INITIAL_CAPACITY];
private final ReentrantLock lock = new ReentrantLock();
private int size = 0;
private Thread leader = null;
private final Condition available = lock.newCondition(); private void siftUp(int k, RunnableScheduledFuture key) {
while (k > 0) {
int parent = (k - 1) >>> 1;
RunnableScheduledFuture e = queue[parent];
if (key.compareTo(e) >= 0)
break;
queue[k] = e;
setIndex(e, k);
k = parent;
}
queue[k] = key;
setIndex(key, k);
} private void siftDown(int k, RunnableScheduledFuture key) {
int half = size >>> 1;
while (k < half) {
int child = (k << 1) + 1;
RunnableScheduledFuture c = queue[child];
int right = child + 1;
if (right < size && c.compareTo(queue[right]) > 0)
c = queue[child = right];
if (key.compareTo(c) <= 0)
break;
queue[k] = c;
setIndex(c, k);
k = child;
}
queue[k] = key;
setIndex(key, k);
} public boolean offer(Runnable x) {
if (x == null)
throw new NullPointerException();
RunnableScheduledFuture e = (RunnableScheduledFuture)x;
final ReentrantLock lock = this.lock;
lock.lock();
try {
int i = size;
if (i >= queue.length)
grow();
size = i + 1;
if (i == 0) {
queue[0] = e;
setIndex(e, 0);
} else {
siftUp(i, e);
}
if (queue[0] == e) {
leader = null;
available.signal();
}
} finally {
lock.unlock();
}
return true;
} public RunnableScheduledFuture take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
RunnableScheduledFuture first = queue[0];
if (first == null)
available.await();
else {
long delay = first.getDelay(TimeUnit.NANOSECONDS);
if (delay <= 0)
return finishPoll(first);
else 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 && queue[0] != null)
available.signal();
lock.unlock();
}
}
}

ScheduledFutureTask是周期任务:

private class ScheduledFutureTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V> {
//当2个task的时间相同时,用来比较task优先级
private final long sequenceNumber;
//任务执行时间 nanoTime units
private long time;
/**
* Period in nanoseconds for repeating tasks. A positive
* value indicates fixed-rate execution. A negative value
* indicates fixed-delay execution. A value of 0 indicates a
* non-repeating task.
*/
private final long period;
/** The actual task to be re-enqueued by reExecutePeriodic */
RunnableScheduledFuture<V> outerTask = this;
// DelayedWorkQueue中堆的下标
int heapIndex; ScheduledFutureTask(Runnable r, V result, long ns, long period) {
super(r, result);
this.time = ns;
this.period = period;
this.sequenceNumber = sequencer.getAndIncrement();
} // 堆在siftUp和siftDown时需要比较大小
public int compareTo(Delayed other) {
if (other == this) // compare zero ONLY if same object
return 0;
if (other instanceof ScheduledFutureTask) {
ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
long diff = time - x.time;
if (diff < 0)
return -1;
else if (diff > 0)
return 1;
else if (sequenceNumber < x.sequenceNumber)
return -1;
else
return 1;
}
long d = (getDelay(TimeUnit.NANOSECONDS) -
other.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
} // 设置周期任务的下一次执行时间
private void setNextRunTime() {
long p = period;
if (p > 0)
time += p;
else
time = triggerTime(-p);
} public boolean cancel(boolean mayInterruptIfRunning) {
boolean cancelled = super.cancel(mayInterruptIfRunning);
if (cancelled && removeOnCancel && heapIndex >= 0)
remove(this);
return cancelled;
} /**
* Overrides FutureTask version so as to reset/requeue if periodic.
*/
public void run() {
boolean periodic = isPeriodic();
if (!canRunInCurrentRunState(periodic))
cancel(false);
else if (!periodic)
ScheduledFutureTask.super.run();
else if (ScheduledFutureTask.super.runAndReset()) {
//设置下次任务的时间
setNextRunTime();
reExecutePeriodic(outerTask);
}
}
} // ScheduledThreadPoolExecutor
void reExecutePeriodic(RunnableScheduledFuture<?> task) {
if (canRunInCurrentRunState(true)) {
super.getQueue().add(task);
if (!canRunInCurrentRunState(true) && remove(task))
task.cancel(false);
else
ensurePrestart();
}
} // ThreadPoolExecutor
void ensurePrestart() {
int wc = workerCountOf(ctl.get());
if (wc < corePoolSize)
addWorker(null, true);
else if (wc == 0)
addWorker(null, false);
}

ScheduledThreadPoolExecutor的更多相关文章

  1. Java 线程 — ScheduledThreadPoolExecutor

    ScheduledThreadPoolExecutor 该类继承自ThreadPoolExecutor,增加了定时执行线程和延迟启动的功能,这两个功能是通过延时队列DelayedWorkQueue辅助 ...

  2. 使用Timer和ScheduledThreadPoolExecutor执行定时任务

    Java使用Timer和ScheduledThreadPoolExecutor执行定时任务 定时任务是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,主要JDK自带的一些 ...

  3. JUC回顾之-ScheduledThreadPoolExecutor底层实现原理和应用

    项目中经常使用定时器,比如每隔一段时间清理下线过期的F码,或者应用timer定期查询MQ在数据库的配置,根据不同version实现配置的实时更新等等.但是timer是存在一些缺陷的,因为Timer在执 ...

  4. 使用java自带的定时任务ScheduledThreadPoolExecutor

    ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类: JDK api里是这么说的: ThreadPoolExecutor,它可另行安排在给定的延迟后运行 ...

  5. Java定时任务Timer、TimerTask与ScheduledThreadPoolExecutor详解

     定时任务就是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,本文从从JDK自带的一些方法来实现定时任务的需求. 一.Timer和TimerTask  Timer和Tim ...

  6. Timer与ScheduledThreadPoolExecutor的比较

    推荐还是用第二种方法,即用ScheduledThreadPoolExecutor,因为它不需要像timer那样需要在里面再用一个线程池来保证计时的准确.(前提是线程池必须要大于1个线程) 1.time ...

  7. Android定时器,推荐ScheduledThreadPoolExecutor

    Android定时器,推荐ScheduledThreadPoolExecutor 官方网址:http://developer.android.com/reference/java/util/Timer ...

  8. Java Concurrency - ScheduledThreadPoolExecutor

    The Executor framework provides the ThreadPoolExecutor class to execute Callable and Runnable tasks ...

  9. Java调度线程池ScheduledThreadPoolExecutor源码分析

    最近新接手的项目里大量使用了ScheduledThreadPoolExecutor类去执行一些定时任务,之前一直没有机会研究这个类的源码,这次趁着机会好好研读一下. 该类主要还是基于ThreadPoo ...

  10. [转载] java多线程学习-java.util.concurrent详解(三)ScheduledThreadPoolExecutor

    转载自http://janeky.iteye.com/blog/770441 ------------------------------------------------------------- ...

随机推荐

  1. C# widget

    Invoke(Delegate)的用法: //例如,要实时update窗体.如果在另一个线程中update,那么可以直接update(可以不在新线程中):也可以在Delegate中给出upate,然后 ...

  2. new和malloc的用法和区别

    从以下几个方面总结下new和malloc的区别: 参考博客: https://blog.csdn.net/nie19940803/article/details/76358673 https://bl ...

  3. 生存分析与R--转载

    生存分析与R 生存分析是将事件的结果和出现这一结果所经历的时间结合起来分析的一类统计分析方法.不仅考虑事件是否出现,而且还考虑事件出现的时间长短,因此这类方法也被称为事件时间分析(time-to-ev ...

  4. 【Cucumber】【问题集锦】

    [问题一]invalid byte sequence in GBK"问题 invalid byte sequence in UTF-8"问题 参考地址:http://fantaxy ...

  5. Centos7安装JDK8以及环境配置

    下载,选择centos7 64位版本 https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.h ...

  6. STL_string.ZC

    1.转成 小写/大写 #include <algorithm>using namespace std; // 转成小写transform(_strAttrNameG.begin(), _s ...

  7. [calss*="col-"]匹配类名中包含col-的类名,^以col-开头,$以col-结尾

    [class*= col-]  代表包含  col-  的类名 , 例 col-md-4 ,demo-col-2(这个是虚构的)等都可以匹配到. [class^=col-]  代表 以 col- 开头 ...

  8. django生成迁移文件

    1.创建虚拟环境 在终端上输入创建python3的虚拟环境 mkvirtualenv -p python3 虚拟环境的名字 安装django和pymysql 2.创建项目创建工程的命令: django ...

  9. Python全栈开发-执行字符串形式的语句和字符串形式的表达式方法(即exec和eval方法)

    Python有时需要动态的创造Python代码,然后将其作为语句执行  或  作为表达式计算. exec用于执行存储在字符串中的Python代码.   1. 语句与表达式的区别:表达式是 某事,语句是 ...

  10. Http Requests for PHP

    一.Requests for PHP 官网:http://requests.ryanmccue.info官方介绍:Requests is a humble HTTP request library. ...