jdk源码读---java.util.Timer

java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new java.util.TimerTask(){
            public void run(){
                System.out.println("yyyyyyy");
            }
        }, calendar.getTime());
        calendar.add(java.util.Calendar.SECOND,10);
        timer.schedule(new java.util.TimerTask(){
            public void run(){
                System.out.println("XXXXXXX");
            }
        }, calendar.getTime());

楼上代码,用timer定时执行了两个任务。

涉及timer的两个操作。一个实例化new,一个时间任务安排schedule

第一个源码实例化,解读:Timer构造设定当前终极TimerThread 的名称;名称中序列采用了原子整形定义;其实就一个;有必要吗?并启动TimerThread 主线程

    private final static AtomicInteger nextSerialNumber = new AtomicInteger(0);
    private static int serialNumber() {
        return nextSerialNumber.getAndIncrement();
    }
    public Timer() {
        this("Timer-" + serialNumber());
    }

private final TimerThread thread = new TimerThread(queue);

      public Timer(String name) {
        thread.setName(name);
        thread.start();
    }

第二个操作

解读:多个schedule方法重载,调sched方法;校验形参,常规操作;

synchronized同步锁定queue(taskqueue)

synchronized同步锁定lock(Timertask),校验timertask,queue加入此任务

 

    public void schedule(TimerTask task, Date time) {
        sched(task, time.getTime(), 0);
    }

private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");
        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }

猜想:先实例化Timer,那Timer实例化,就把主线程起了;主线程就开始干活;接着往Timer.shedule跑,往队列里面注入任务。

回头想主线程干活是干啥活;说不定主线程这时候在你加入的时候正忙着;主线程是死循环读取队列最临近任务执行;

解读下面源码:死循环读取任务;同步锁定队列,死循环检查队列,若空且线程未死等待;等待唤醒;

若执行过程跳入,队列又空了,直接退出,不执行,等待垃圾回收,执行finalize方法;

队列未空,主线程未死,取队列(堆)最小,判断执行时间是否到,到了或者过了直接执行,且任务执行是在队列锁和任务锁外面。要不是就queue.wait(executionTime - currentTime);等待,等待让出队列的锁。队列可操作,加入任务。若加入任务比当前的快,那就notify;

第一个wait等待timer中schedule加入任务时检查是第一个任务调用notify唤醒

第二个wait(executionTime - currentTime),也是由其楼上唤醒;若没有楼上的唤醒;那就是队列没人用。自己给自己抢占回来

private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
                    if (queue.isEmpty())
                        break;
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue; 
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else {
                                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.run();
            } catch(InterruptedException e) {
            }
        }
    }
}

另外一个点:

解读:垃圾回收,有空在品味下。不是很确定

    private final Object threadReaper = new Object() {
        protected void finalize() throws Throwable {
            synchronized(queue) {
                thread.newTasksMayBeScheduled = false;
                queue.notify(); // In case queue is empty.
            }
        }
    };

下面解读里面设计的几个大咖

1、//TimerThread(主线程)
        //带了个newTasksMayBeScheduled标识线程死了没
        //带了个成员属性TaskQueue队列,由timer提供注入
        //run死循环
        //循环读取TaskQueue队列第一个需要执行的Timetask,Timetask.run()执行
        
   2、//TimerTask(任务线程)
        //带了个nextExecutionTime标识任务什么时间点执行
        //带了个period重复执行频率
        //带了个lock对象锁任务里面修改内部成员必须得到锁,感觉没必要
        //run方法自己重写
        
   3、/**
         * This class represents a timer task queue: a priority queue of TimerTasks,
         * ordered on nextExecutionTime.  Each Timer object has one of these, which it
         * shares with its TimerThread.  Internally this class uses a heap, which
         * offers log(n) performance for the add, removeMin and rescheduleMin
         * operations, and constant time performance for the getMin operation.
         */
        //英语主要意思:
        //它担任timer的任务队列;有且仅有一个;并注入TimerThread主线程;
        //nextExecutionTime排序
        //本质性,堆(跟树不一样,左右有大小。它就小到大)思想,add, removeMin and rescheduleMin,log(n)复杂度,getMin常量级复杂度
        
        //TaskQueue(队列)
        //数组充当队列,TimerTask[] queue = new TimerTask[128];加载不初始化cinit
        //各个成员方法,常规操作;主要看下面三个
    堆排序,平衡二叉最小堆(同层节点或子树高度的数量不超过1的差别,堆左右节点比父亲节点大)

fixUp 

解读:由下往上比对,知道k=1为止;k取一半为父亲。数组标示堆;满足比父亲小跳出。比父亲大,交换位置。

    private void fixUp(int k) {
        while (k > 1) {
            int j = k >> 1;
            if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

fixDown

解读:由上往下比对。当前节点索引乘以2即是;先比对当前节点下左右节点小的一个。如果比小的大换;

private void fixDown(int k) {
        int j;
        while ((j = k << 1) <= size && j > 0) {
            if (j < size &&
                queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
                j++; // j indexes smallest kid
            if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

heapify

解读:全堆重排序,最大的数节点,除以2就是当前父亲,也是最大需要排序的节点。往下排序。

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

你可能感兴趣的:(jdk源码读)