Java线程—Timer类的使用

《》java.util.Timer是一个线程定时调度类,用来定时触发指定的任务

《》在Timer类中的成员域中含有一个TaskQueue 和 一个TimerThread

也就是说这个Timer的实例对象实际上是一个后台线程对象;这个TimerThread不断地从TaskQueue中取任务来执行

《》使用这个类的方法非常的简单:

1、创建一个TimerTask的子类,这个子类就是用来提交给Timer的循环执行的任务对象,这个TimerTask继承了Runnable接口,因此创建这个子类的时候,我们需要重写run()方法;

2、创建一个Timer对象,将上面创建的TimerTask任务提交给这个对象,并指定时间规则,这样就能够循环执行了

3、当然我们也可以在run方法中使用sleep来使任务定期延时执行

示例:

import java.util.Date;
import java.util.TimerTask;
import java.util.Timer;
class PlainTimerTask extends TimerTask {
@Override
public void run() {
System.out.println(new Date());
}
}
public class TimerRunner {
public static void main(String [] args){
Timer timer=new Timer();
timer.schedule(new PlainTimerTask(), 0,5000,);
    }
}

这样一来任务就能够每隔5s执行一次

《》方法简介:

1.构造方法

Timer()

Creates a new   timer.

Timer(boolean isDaemon)

Creates a new   timer whose associated thread may be specified to run as a daemon.

Timer(String name)

Creates a new   timer whose associated thread has the specified name.

Timer(String name, boolean isDaemon)

Creates a new   timer whose associated thread has the specified name, and may be specified to   run as a daemon

默认的Timer线程是非守候线程,也就说,当主线程结束后,Timer线程还要继续执行;

2、此外还有多个重载的schedule()、 scheduleAtFixedRate()方法,用来指定实行的时间规则,可查阅官方文档

 

posted @ 2014-10-26 08:44  RoperLee  阅读(311)  评论(0)    收藏  举报