publicclassTimer{ /** * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. */ privatefinal TaskQueue queue = new TaskQueue();
/** * The timer thread. */ privatefinal TimerThread thread = new TimerThread(queue);
/** * Timer中有多个schedule重载方法,里面都调用了sched方法 */ publicvoidschedule(TimerTask task, long delay){ if (delay < 0) thrownew IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); } /** * * Timer是一个中介者,通过sched方法统一协调TimerTask * * @param task 被协调的对象 * @param time * @param period */ privatevoidsched(TimerTask task, long time, long period){ if (time < 0) thrownew IllegalArgumentException("Illegal execution time."); // Constrain value of period sufficiently to prevent numeric // overflow while still being effectively infinitely large. if (Math.abs(period) > (Long.MAX_VALUE >> 1)) period >>= 1; synchronized(queue) { if (!thread.newTasksMayBeScheduled) thrownew IllegalStateException("Timer already cancelled."); synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) thrownew 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(); } } }