Timer使用线程机制来实现,每个Timer对象后有一个后台线程,这个后台线程来执行该Timer对象的所用TimeTask任务。
Timer代码中有后台线程实例:
/**
* 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.
*/
private TaskQueue queue = new TaskQueue();
/**
* The timer thread.
*/
private TimerThread thread = new TimerThread(queue);
这就是一个生产者消费者模式,Timer生产TimerTask任务放到TaskQueue 中,然后TimerThread从这个TaskQueue中取任务来进行执行。
A facility for threads to schedule tasks for future execution in a
background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
Corresponding to each Timer object is a single background
thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly.
Timer t = new Timer();
Calendar date1 = Calendar.getInstance();
date1.add(Calendar.MILLISECOND, 1000);
t.schedule(new TimerTask(){
@Override
public void run() {
System.out.println("3");
System.out.println("线程t1:" + Thread.currentThread().getId());
}
}, date1.getTime());
Timer t2 = new Timer();
Calendar date2 = Calendar.getInstance();
date2.add(Calendar.MILLISECOND, 1000);
t2.schedule(new TimerTask(){
@Override
public void run() {
System.out.println("4");
System.out.println("线程t2:" + Thread.currentThread().getId());
}
}, date2.getTime());
System.out.println("主线程:" + Thread.currentThread().getId());
System.out.println("1");
输出:
主线程:1
1
3
4
线程t1:8
线程t2:9