当前位置: 代码迷 >> 综合 >> java中的定时器以及schedule和scheduleAtFixedRate方法的探究
  详细解决方案

java中的定时器以及schedule和scheduleAtFixedRate方法的探究

热度:49   发布时间:2024-01-18 23:08:55.0
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;public class TimeTaskClass {private static int count = 0;public static void main(String[] args) {// 一秒后启动,此后固定频率3秒响一次new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.out.println("叮叮叮!");}}, 1000, 3000);//交替执行响铃class MyTimerTask extends TimerTask {@Overridepublic void run() { // 生成0和1 count = (count + 1) % 2;System.out.println("叮叮叮!"); // 每2秒和4秒交替响铃new Timer().schedule(new MyTimerTask(), 2000 + 2000 * count);}}// 两秒后启动响铃任务new Timer().schedule(new MyTimerTask(), 2000);// 在固定的日期启动,以后每隔1秒执行一次SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Date startDate = null;try {startDate = dateFormatter.parse("2013/8/3 12:33:00");} catch (ParseException e1) {e1.printStackTrace();}new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.out.println("叮叮叮");}}, startDate, 1000);// 固定日期// Timer的schedule和scheduleAtFixedRate方法的区别new Timer().schedule(new TimerTask() {@Overridepublic void run() {try {Thread.sleep(2000);//延迟看效果} catch (InterruptedException e) { // TODO Auto-generated catch// blocke.printStackTrace();}System.out.println("响铃成功最近实际 执行的已安排 执行时间为:"+ this.scheduledExecutionTime());}}, 2000, 1000);// 打印结果//51//52//53//54//响铃成功最近实际 执行的已安排 执行时间为:1375504973656//55//56//响铃成功最近实际 执行的已安排 执行时间为:1375504975656//57//58//响铃成功最近实际 执行的已安排 执行时间为:1375504977656new Timer().scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {try {Thread.sleep(2000);//延迟看效果} catch (InterruptedException e) { // TODO Auto-generated catch// blocke.printStackTrace();}System.out.println("响铃成功最近实际 执行的已安排 执行时间为:"+ this.scheduledExecutionTime());}}, 2000, 1000);// 打印结果//43//44//45//46//响铃成功最近实际 执行的已安排 执行时间为:1375504905953//47//48//响铃成功最近实际 执行的已安排 执行时间为:1375504906953//49//50//响铃成功最近实际 执行的已安排 执行时间为:1375504907953//总结://schedule方法:下一次执行时间相对于 上一次 实际执行完成的时间点 ,因此执行时间会不断延后,下一次的执行时间点=上一次程序执行完成的时间点+间隔时间 //scheduleAtFixedRate方法:下一次执行时间相对于上一次开始的 时间点 ,因此执行时间不会延后,存在并发性 ,下一次的执行时间点=上一次程序开始执行的时间点+间隔时间,因为可能时间覆盖,需要考虑同步while (true) {// 生成秒计数方便观察System.out.println(new Date().getSeconds());try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}