java timerTask timer分析

首先看一看 timer timerTask如何调用 ?



Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("哈哈 我正在运行;");
}
} ;
timer.schedule(task,1,100);

一个非常简单的例子。首先我们看下 TimerTask的结构:
public abstract class TimerTask implements Runnable {

final Object lock = new Object();//将对象当做一个锁来处理

int state = VIRGIN;//线程的状态

static final int VIRGIN = 0;

static final int SCHEDULED = 1;

static final int EXECUTED = 2;

static final int CANCELLED = 3;

long nextExecutionTime;

long period = 0;

protected TimerTask() {
}

public boolean cancel() {
synchronized(lock) {
boolean result = (state == SCHEDULED);
state = CANCELLED;
return result;
}
}


public long scheduledExecutionTime() {
synchronized(lock) {
return (period < 0 ? nextExecutionTime + period
: nextExecutionTime - period);
}
}
}

先看一看 timer timerTask如何调用 ? TimerTask仅仅实现了Runnable。
public class Timer {

private TaskQueue queue = new TaskQueue(); //存放任务的

private TimerThread thread = new TimerThread(queue);

}

这里非常重要的一个类是:TimerThread

请看他的处理机制:
private void mainLoop() {
while (true) {
//....do something
}
}

实际上TimerThread的机制是死循环调用,当发现队列中存在任务则执行。


好 现在来分析下 任务处理的周期机制

请看如下代码:

[align=left]
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
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) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
//这里需要重新调用queue里的执行顺序
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) {
}
[/align]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值