JAVA Timer 定时器原理

来源:互联网 发布:淘宝店铺怎么分享连接 编辑:程序博客网 时间:2024/05/09 05:04

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) {
  }

 }

}

 

 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 前向运动精子少怎么办 精子前向运动力低怎么办 精子异常形态率高怎么办 精子正常率才1%怎么办 精子头部缺陷率高怎么办 前向运动精子15%怎么办 精子向前运动力低怎么办 前向运动精子10%怎么办 前向运动精子12%怎么办 前向运动精子2%怎么办 正常精子形态只有10%怎么办 精子混合畸形率高怎么办 正常形态精子才2怎么办 精子密度低至0.8怎么办 精子总活动率低怎么办 前向运动精子低怎么办 精子畸形率百分之94怎么办 实验室授权签字人考不过怎么办 万和热水器排污口漏水怎么办 万和热水器水箱漏水怎么办 军训鞋大了怎么办妙招 麽稍神经不好受怎么办 绒面高跟鞋太硬怎么办 新买的鞋子太硬怎么办 鞋底太硬脚掌疼怎么办 耐克鞋子走路吱吱响怎么办 两只鞋子有色差怎么办 劳保鞋鞋底太硬怎么办 在学校校服丢了怎么办 高中没进重点班怎么办 孩子不懂学不想学怎么办 孩子小学数学学不懂怎么办 入学籍系统提交了没分班怎么办 被监考老师抓了作弊怎么办 作弊被老师抓到了怎么办? 中考作弊给抓到怎么办 考试作弊证据没得监控怎么办 考试作弊被领导发现了怎么办 黄冈讲课视频看不了怎么办 高中学校不给转学籍怎么办 兴山香溪大酒店欠钱不还怎么办