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. React Native组件之BackAndroid !安卓手机的物理返回键的使用

    ok!在安卓手机上,当我们用物理返回键的时候,会以一次性的将程序退出来,这样是很不好的体验,所以就需要使用RN的物理返回键组件:BackAndroid,其原理也就是 分析路由,然后pop()这样! o ...

  2. Codeforces 765 E. Tree Folding

    题目链接:http://codeforces.com/problemset/problem/765/E $DFS子$树进行$DP$ 大概分以下几种情况: 1.为叶子,直接返回. 2.长度不同的路径长度 ...

  3. git difftool和mergetool图形化

    1.当然是先安装Beyond Compare3 (此处省略安装步骤,自行百度) 2.设置difftool git config --global diff.tool bc3 git config -- ...

  4. 导入dmp文件时,需要删除原有ORACLE数据库实例

    导入dmp文件时,对于已存在的数据库实例及表处理方式:删除实例. 1.以管理员身份登录 sqlplus / as sysdba 2.停止实例 shutdown abort; 执行结果:ORACLE i ...

  5. DAY2 初识python

    一.编程语言介绍 1.1 机器语言:直接用计算机能理解的二进制指令编写程序,直接控制硬件 1.2 汇编语言:用英文标签取代二进制指令取编写程序,本质也是在直接控制硬件 1.3 高级语言:用人能理解的表 ...

  6. JS client(X,Y)、screen(X,Y)、page(X,Y)的区别

    clientX:光标相对于当前窗口的水平位置: clientY :光标相对于当前窗口的垂直位置: screenX :光标相对于该屏幕的水平位置: screenY:光标相对于该屏幕的垂直位置: page ...

  7. centos 7 安装jdk1.8

    首先下载jdk1.8  去官网下载jdk:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151. ...

  8. Python 百分比计算

    遇到计算百分比的情况,查了一下,有两种方式 具体实现方式见下面代码 # 方式1 格式化为float ,然后 处理成%格式, 需要对分子/分母 * 100如下, percentList.append(' ...

  9. js正则表达式的积累

    验证数字:^[0-9]*$ 验证n位的数字:^\d{n}$ 验证至少n位数字:^\d{n,}$ 验证m-n位的数字:^\d{m,n}$ 验证零和非零开头的数字:^(0|[1-9][0-9]*)$ 验证 ...

  10. Win7无法保存共享帐户密码

    每次机器重启完之后,网络共享的密码总是要重新输入. [记住我的凭据]选项不起作用. 查到了下面百度经验的文章,挺靠谱的. https://jingyan.baidu.com/article/59a01 ...