Thread和TimerTask
Thread
TimerTask
这是一个任务
可以看到他们都实现了Runnable接口.
但是TimerTask是一个abstract类。
TimerTask的主要方法
如果想让TimerTask执行任务只需要重写run方法。
Timer
官方API的介绍:
示例代码:
package timerTest;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
class TaskA extends TimerTask{
@Override
public void run() {
try {
System.out.println("A begin timer= "+new Date());
Thread.sleep(2000);//模拟耗时2s
System.out.println("A end timer= "+new Date());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println("当前时间:"+new Date());
Calendar calendarRef=Calendar.getInstance();
calendarRef.add(Calendar.SECOND, 10);//十秒之后执行
Date runDate=calendarRef.getTime();
System.out.println("计划时间:"+runDate);
TimerTask task=new TaskA();
Timer timer=new Timer("myTimer");
timer.schedule(task, runDate, 4000);//每隔4s执行一次
}
}
运行结果:
当前时间:Thu Oct 12 12:33:40 GMT+08:00 2017
计划时间:Thu Oct 12 12:33:50 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:50 GMT+08:00 2017
A end timer= Thu Oct 12 12:33:52 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:54 GMT+08:00 2017
A end timer= Thu Oct 12 12:33:56 GMT+08:00 2017
A begin timer= Thu Oct 12 12:33:58 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:00 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:02 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:04 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:06 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:08 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:10 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:12 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:14 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:16 GMT+08:00 2017
A begin timer= Thu Oct 12 12:34:18 GMT+08:00 2017
A end timer= Thu Oct 12 12:34:20 GMT+08:00 2017