`

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]

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics