Jdk中的Timer

来源:互联网 发布:合肥数码美工招聘信息 编辑:程序博客网 时间:2024/06/05 10:52

Daemon(守护线程)的作用是为其他线程的运行提供服务,比如说GC线程。其实User Thread线程和Daemon Thread守护线程本质上来说去没啥区别的,唯一的区别之处就在虚拟机的离开:如果User Thread全部撤离,那么Daemon Thread也就没啥线程好服务的了,所以虚拟机也就退出了。

import java.util.Timer;import java.util.TimerTask;class Reminder {    public Reminder(int i) {        final Timer timer = new Timer();        TimerTask task = new TimerTask() {            @Override            public void run() {                System.out.println("begin");                timer.cancel();            }        };        timer.schedule(task, i * 1000);    }}public class TestTimer {    public static void main(String[] args) {        System.out.println("about to schedule task");        new Reminder(3);        System.out.println("Task schedule");    }}

结果:

about to schedule task
Task schedule
begin

一个timer应该有这些

java.util.Timer timer = new java.util.Timer(true); // true 说明这个timer以daemon方式运行(优先级低, // 程序结束timer也自动结束),注意,javax.swing // 包中也有一个Timer类,如果import中用到swing包, // 要注意名字的冲突。 TimerTask task = new TimerTask() { public void run() { ... //每次需要执行的代码放到这里面。 } }; //以下是几种调度task的方法: timer.schedule(task, time); // time为Date类型:在指定时间执行一次。 timer.schedule(task, firstTime, period); // firstTime为Date类型,period为long // 从firstTime时刻开始,每隔period毫秒执行一次。 timer.schedule(task, delay) // delay 为long类型:从现在起过delay毫秒执行一次 timer.schedule(task, delay, period) // delay为long,period为long:从现在起过delay毫秒以后,每隔period // 毫秒执行一次。

关于cancel方式终止线程

public void cancel() {        synchronized(queue) {            thread.newTasksMayBeScheduled = false;            queue.clear();            queue.notify();  // In case queue was already empty.        }    }

没有显式的线程stop方法,而是调用了queue的clear方法和queue的notify方法,clear是个自定义方法,notify是Objec自带的方法,很明显是去唤醒wait方法的。

再看clear方法:

void clear() {        // Null out task references to prevent memory leak        for (int i=1; i<=size; i++)            queue[i] = null;        size = 0;    }

clear方法很简单,就是去清空queue,queue是一个TimerTask的数组,然后把queue的size重置成0,变成empty.还是没有看到显式的停止线程方法,回到最开始new Timer的时候,看看new Timer代码:

public Timer() {        this("Timer-" + serialNumber());    }    public Timer(String name) {        thread.setName(name);        thread.start();    }

看看这个内部变量thread:

//The timer thread.private TimerThread thread = new TimerThread(queue);

不是原生的Thread,是自定义的类TimerThread.这个类实现了Thread类,重写了run方法,如下:

public void run() {        try {            mainLoop();        } finally {            // Someone killed this Thread, behave as if Timer cancelled            synchronized(queue) {                newTasksMayBeScheduled = false;                queue.clear();  // Eliminate obsolete references            }        }    }

最后是这个mainLoop方法,这方法比较长,截取开头一段:

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

可以看到wait方法,之前的notify就是通知到这个wait,然后clear方法在notify之前做了清空数组的操作,所以会break,线程执行结束,退出。