Timer定時器

TimerTask的源碼以下,由此能夠看到TimerTask是一個抽象類,run方法未實現,須要繼承的子類本身決定run行爲執行什麼樣的任務。
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 abstract void run();//未實現的方法,具體子類實現run方法

    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的源碼以下:Timer類中維護一個任務隊列、一個TimerThread。TimerThread線程裏面也有TaskQueue,    
public class Timer {
    private final TaskQueue queue;
    private final TimerThread thread;
    private final Object threadReaper;
    private static final AtomicInteger nextSerialNumber = new AtomicInteger(0);

    private static int serialNumber() {
        return nextSerialNumber.getAndIncrement();
    }

    public Timer() {
        this("Timer-" + serialNumber());
    }

    public Timer(boolean var1) {
        this("Timer-" + serialNumber(), var1);
    }

    public Timer(String var1) {
        this.queue = new TaskQueue();
        this.thread = new TimerThread(this.queue);
        this.threadReaper = new Object() {
            protected void finalize() throws Throwable {
                synchronized(Timer.this.queue) {
                    Timer.this.thread.newTasksMayBeScheduled = false;
                    Timer.this.queue.notify();
                }
            }
        };
        this.thread.setName(var1);
        this.thread.start();
    }
......
}
class TimerThread extends Thread {
  boolean newTasksMayBeScheduled = true;
 private TaskQueue queue;
TimerThread(TaskQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            mainLoop();
        } finally {
            // Someone killed this Thread, behave as if Timer cancelled
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }
//主循環,定時功能的實現就在這裏,首先獲取queue的鎖,而後獲取隊頭的任務,task加鎖,判斷是否cancelled,若是未cancelled
//executionTime爲任務指定執行時間,判斷若是executionTime<=currentTime,直接移出隊頭,不然從新reschedule,
//將任務從新放在什麼時候的位置(Queue.fixDown方法)
private void mainLoop() {
        while (true) {
            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.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) {
            }
        }
    }
}