/**
* 普通thread
* 这是最常见的,创建一个thread,然后让它在while循环里一直运行着,
* 通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:
* @author GT
*
*/publicclassTask1 {publicstaticvoidmain(String[] args) {
// run in a second finallong timeInterval = 1000;
Runnable runnable = new Runnable() {
publicvoidrun() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
import java.util.Timer;
import java.util.TimerTask;
/**
*
* 于第一种方式相比,优势 1>当启动和去取消任务时可以控制 2>第一次执行任务时可以指定你想要的delay时间
*
* 在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。 Timer实例可以调度多任务,它是线程安全的。
* 当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。 下面是代码:
*
* @author GT
*
*/publicclassTask2 {publicstaticvoidmain(String[] args) {
TimerTask task = new TimerTask() {
@Overridepublicvoidrun() {
// task to run goes here
System.out.println("Hello !!!");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
// schedules the task to be run in an interval
timer.scheduleAtFixedRate(task, delay, intevalPeriod);
} // end of main
}