JAVA Timer 定时器原理

1、Timer 组成:TaskQueue  TimerThread

TaskQueue  是用来存储 TimerTask  ,TimerTask 是Runnable 子类

class TaskQueue
{
  private TimerTask[] queue = new TimerTask[128];
  private int size = 0;

  int size()
  {
    return this.size;
  }

  void add(TimerTask paramTimerTask)
  {
    if (this.size + 1 == this.queue.length)
      this.queue = ((TimerTask[])Arrays.copyOf(this.queue, 2 * this.queue.length));
    this.queue[(++this.size)] = paramTimerTask;
    fixUp(this.size);
  }

  TimerTask getMin()
  {
    return this.queue[1];
  }

  TimerTask get(int paramInt)
  {
    return this.queue[paramInt];
  }

  void removeMin()
  {
    this.queue[1] = this.queue[this.size];
    this.queue[(this.size--)] = null;
    fixDown(1);
  }

  void quickRemove(int paramInt)
  {
    assert (paramInt <= this.size);
    this.queue[paramInt] = this.queue[this.size];
    this.queue[(this.size--)] = null;
  }

  void rescheduleMin(long paramLong)
  {
    this.queue[1].nextExecutionTime = paramLong;
    fixDown(1);
  }

  boolean isEmpty()
  {
    return (this.size == 0);
  }

  void clear()
  {
    for (int i = 1; i <= this.size; ++i)
      this.queue[i] = null;
    this.size = 0;
  }

  private void fixUp(int paramInt)
  {
    while (paramInt > 1)
    {
      int i = paramInt >> 1;
      if (this.queue[i].nextExecutionTime <= this.queue[paramInt].nextExecutionTime)
        return;
      TimerTask localTimerTask = this.queue[i];
      this.queue[i] = this.queue[paramInt];
      this.queue[paramInt] = localTimerTask;
      paramInt = i;
    }
  }

  private void fixDown(int paramInt)
  {
    while (((i = paramInt << 1) <= this.size) && (i > 0))
    {
      int i;
      if (((i < this.size) && (this.queue[i].nextExecutionTime > this.queue[(i + 1)].nextExecutionTime)) || (this.queue[paramInt].nextExecutionTime <= this.queue[(++i)].nextExecutionTime))
        return;
      TimerTask localTimerTask = this.queue[i];
      this.queue[i] = this.queue[paramInt];
      this.queue[paramInt] = localTimerTask;
      paramInt = i;
    }
  }

  void heapify()
  {
    for (int i = this.size / 2; i >= 1; --i)
      fixDown(i);
  }
}

 TimerThread 只是一个线程,用来执TaskQueue里面的TimerTask  里面的run方法而不是start方法.

package java.util;

class TimerThread extends Thread
{
  boolean newTasksMayBeScheduled = true;
  private TaskQueue queue;

  TimerThread(TaskQueue paramTaskQueue)
  {
    this.queue = paramTaskQueue;
  }

  public void run()
  {
    try
    {
      mainLoop();
    }
    finally
    {
      synchronized (this.queue)
      {
        this.newTasksMayBeScheduled = false;
        this.queue.clear();
      }
    }
  }

  private void mainLoop()
  {
    while (true)
      try
      {
        TimerTask localTimerTask;
        int i;
        synchronized (this.queue)
        {
          while ((this.queue.isEmpty()) && (this.newTasksMayBeScheduled))
            this.queue.wait();
          if (this.queue.isEmpty())
            return;
          localTimerTask = this.queue.getMin();
          long l1;
          long l2;
          synchronized (localTimerTask.lock)
          {
            if (localTimerTask.state == 3)
            {
              this.queue.removeMin();
              monitorexit;
            }
            l1 = System.currentTimeMillis();
            l2 = localTimerTask.nextExecutionTime;
            if ((i = (l2 <= l1) ? 1 : 0) != 0)
              if (localTimerTask.period == 0L)
              {
                this.queue.removeMin();
                localTimerTask.state = 2;
              }
              else
              {
                this.queue.rescheduleMin((localTimerTask.period < 0L) ? l1 - localTimerTask.period : l2 + localTimerTask.period);
              }
          }
          if (i == 0)
            this.queue.wait(l2 - l1);
        }
        if (i != 0)
          localTimerTask.run();
      }
      catch (InterruptedException localInterruptedException)
      {
      }
  }
}

2、里面的算法 生产者与消费者模式

3、可能存在的引起的问题就是TimerTask 执行会延迟。

4、TimerTask使用例子及实验测试说明(延迟性)

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Timer t = new Timer();
  for(int i=1 ;i<101; i++){   
   MyTimerTask  mtt = new MyTimerTask("线程"+i+": ");
   t.schedule(mtt, 2000);
  }
 }
}

class MyTimerTask extends TimerTask {
 String s;
 public MyTimerTask(String s) {
  this.s = s;
 }
 public void run() {
  try {
   Random random = new Random();
   for (int i = 0; i < 10; i++) {
    int longTime = random.nextInt(10000);
    Thread.sleep(longTime);
    System.out.println(s + i + "  waitTime=" +longTime);
   }
  } catch (Exception e) {
  }

 }

}

 

 

你可能感兴趣的:(JAVA Timer 定时器原理)