当前位置: 移动技术网 > IT编程>开发语言>Java > 解析Java中的定时器及使用定时器制作弹弹球游戏的示例

解析Java中的定时器及使用定时器制作弹弹球游戏的示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

  在我们编程过程中如果需要执行一些简单的定时任务,无须做复杂的控制,我们可以考虑使用jdk中的timer定时任务来实现。下面lz就其原理、实例以及timer缺陷三个方面来解析java timer定时器。

一、简介
      在java中一个完整定时任务需要由timer、timertask两个类来配合完成。 api中是这样定义他们的,timer:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。由timertask:timer 安排为一次执行或重复执行的任务。我们可以这样理解timer是一种定时器工具,用来在一个后台线程计划执行指定任务,而timertask一个抽象类,它的子类代表一个可以被timer计划的任务。
timer类
      在工具类timer中,提供了四个构造方法,每个构造方法都启动了计时器线程,同时timer类可以保证多个线程可以共享单个timer对象而无需进行外部同步,所以timer类是线程安全的。但是由于每一个timer对象对应的是单个后台线程,用于顺序执行所有的计时器任务,一般情况下我们的线程任务执行所消耗的时间应该非常短,但是由于特殊情况导致某个定时器任务执行的时间太长,那么他就会“独占”计时器的任务执行线程,其后的所有线程都必须等待它执行完,这就会延迟后续任务的执行,使这些任务堆积在一起,具体情况我们后面分析。
      当程序初始化完成timer后,定时任务就会按照我们设定的时间去执行,timer提供了schedule方法,该方法有多中重载方式来适应不同的情况,如下:
      schedule(timertask task, date time):安排在指定的时间执行指定的任务。
      schedule(timertask task, date firsttime, long period) :安排指定的任务在指定的时间开始进行重复的固定延迟执行。
      schedule(timertask task, long delay) :安排在指定延迟后执行指定的任务。
      schedule(timertask task, long delay, long period) :安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
      同时也重载了scheduleatfixedrate方法,scheduleatfixedrate方法与schedule相同,只不过他们的侧重点不同,区别后面分析。
      scheduleatfixedrate(timertask task, date firsttime, long period):安排指定的任务在指定的时间开始进行重复的固定速率执行。
      scheduleatfixedrate(timertask task, long delay, long period):安排指定的任务在指定的延迟后开始进行重复的固定速率执行。
timertask
      timertask类是一个抽象类,由timer 安排为一次执行或重复执行的任务。它有一个抽象方法run()方法,该方法用于执行相应计时器任务要执行的操作。因此每一个具体的任务类都必须继承timertask,然后重写run()方法。
      另外它还有两个非抽象的方法:
      boolean cancel():取消此计时器任务。
      long scheduledexecutiontime():返回此任务最近实际执行的安排执行时间。

二、实例
2.1、指定延迟时间执行定时任务

public class timertest01 { 
 timer timer; 
 public timertest01(int time){ 
  timer = new timer(); 
  timer.schedule(new timertasktest01(), time * 1000); 
 } 
  
 public static void main(string[] args) { 
  system.out.println("timer begin...."); 
  new timertest01(3); 
 } 
} 
 
public class timertasktest01 extends timertask{ 
 
 public void run() { 
  system.out.println("time's up!!!!"); 
 } 
} 

运行结果:

首先打印:

timer begin.... 

 
3秒后打印:

time's up!!!! 

2.2、在指定时间执行定时任务

public class timertest02 { 
 timer timer; 
  
 public timertest02(){ 
  date time = gettime(); 
  system.out.println("指定时间time=" + time); 
  timer = new timer(); 
  timer.schedule(new timertasktest02(), time); 
 } 
  
 public date gettime(){ 
  calendar calendar = calendar.getinstance(); 
  calendar.set(calendar.hour_of_day, 11); 
  calendar.set(calendar.minute, 39); 
  calendar.set(calendar.second, 00); 
  date time = calendar.gettime(); 
   
  return time; 
 } 
  
 public static void main(string[] args) { 
  new timertest02(); 
 } 
} 
 
public class timertasktest02 extends timertask{ 
 
 @override 
 public void run() { 
  system.out.println("指定时间执行线程任务..."); 
 } 
} 

当时间到达11:39:00时就会执行该线程任务,当然大于该时间也会执行!!执行结果为:

指定时间time=tue jun 10 11:39:00 cst 2014 
指定时间执行线程任务... 

2.3、在延迟指定时间后以指定的间隔时间循环执行定时任务

public class timertest03 { 
 timer timer; 
  
 public timertest03(){ 
  timer = new timer(); 
  timer.schedule(new timertasktest03(), 1000, 2000); 
 } 
  
 public static void main(string[] args) { 
  new timertest03(); 
 } 
} 
 
public class timertasktest03 extends timertask{ 
 
 @override 
 public void run() { 
  date date = new date(this.scheduledexecutiontime()); 
  system.out.println("本次执行该线程的时间为:" + date); 
 } 
} 

运行结果:

本次执行该线程的时间为:tue jun 10 21:19:47 cst 2014 
本次执行该线程的时间为:tue jun 10 21:19:49 cst 2014 
本次执行该线程的时间为:tue jun 10 21:19:51 cst 2014 
本次执行该线程的时间为:tue jun 10 21:19:53 cst 2014 
本次执行该线程的时间为:tue jun 10 21:19:55 cst 2014 
本次执行该线程的时间为:tue jun 10 21:19:57 cst 2014 
................. 

      对于这个线程任务,如果我们不将该任务停止,他会一直运行下去。
      对于上面三个实例,lz只是简单的演示了一下,同时也没有讲解scheduleatfixedrate方法的例子,其实该方法与schedule方法一样!
2.4、分析schedule和scheduleatfixedrate
(1)schedule(timertask task, date time)、schedule(timertask task, long delay)
      对于这两个方法而言,如果指定的计划执行时间scheduledexecutiontime<= systemcurrenttime,则task会被立即执行。scheduledexecutiontime不会因为某一个task的过度执行而改变。
(2)schedule(timertask task, date firsttime, long period)、schedule(timertask task, long delay, long period)
      这两个方法与上面两个就有点儿不同的,前面提过timer的计时器任务会因为前一个任务执行时间较长而延时。在这两个方法中,每一次执行的task的计划时间会随着前一个task的实际时间而发生改变,也就是scheduledexecutiontime(n+1)=realexecutiontime(n)+periodtime。也就是说如果第n个task由于某种情况导致这次的执行时间过程,最后导致systemcurrenttime>= scheduledexecutiontime(n+1),这是第n+1个task并不会因为到时了而执行,他会等待第n个task执行完之后再执行,那么这样势必会导致n+2个的执行实现scheduledexecutiontime放生改变即scheduledexecutiontime(n+2) = realexecutiontime(n+1)+periodtime。所以这两个方法更加注重保存间隔时间的稳定。
(3)scheduleatfixedrate(timertask task, date firsttime, long period)、scheduleatfixedrate(timertask task, long delay, long period)
      在前面也提过scheduleatfixedrate与schedule方法的侧重点不同,schedule方法侧重保存间隔时间的稳定,而scheduleatfixedrate方法更加侧重于保持执行频率的稳定。为什么这么说,原因如下。在schedule方法中会因为前一个任务的延迟而导致其后面的定时任务延时,而scheduleatfixedrate方法则不会,如果第n个task执行时间过长导致systemcurrenttime>= scheduledexecutiontime(n+1),则不会做任何等待他会立即执行第n+1个task,所以scheduleatfixedrate方法执行时间的计算方法不同于schedule,而是scheduledexecutiontime(n)=firstexecutetime +n*periodtime,该计算方法永远保持不变。所以scheduleatfixedrate更加侧重于保持执行频率的稳定。

三、timer的缺陷
3.1、timer的缺陷
      timer计时器可以定时(指定时间执行任务)、延迟(延迟5秒执行任务)、周期性地执行任务(每隔个1秒执行任务),但是,timer存在一些缺陷。首先timer对调度的支持是基于绝对时间的,而不是相对时间,所以它对系统时间的改变非常敏感。其次timer线程是不会捕获异常的,如果timertask抛出的了未检查异常则会导致timer线程终止,同时timer也不会重新恢复线程的执行,他会错误的认为整个timer线程都会取消。同时,已经被安排单尚未执行的timertask也不会再执行了,新的任务也不能被调度。故如果timertask抛出未检查的异常,timer将会产生无法预料的行为。
(1)timer管理时间延迟缺陷
      前面timer在执行定时任务时只会创建一个线程任务,如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间,会发生一些缺陷:

public class timertest04 { 
 private timer timer; 
 public long start;  
  
 public timertest04(){ 
  this.timer = new timer(); 
  start = system.currenttimemillis(); 
 } 
  
 public void timerone(){ 
  timer.schedule(new timertask() { 
   public void run() { 
    system.out.println("timerone invoked ,the time:" + (system.currenttimemillis() - start)); 
    try { 
     thread.sleep(4000); //线程休眠3000 
    } catch (interruptedexception e) { 
     e.printstacktrace(); 
    } 
   } 
  }, 1000); 
 } 
  
 public void timertwo(){ 
  timer.schedule(new timertask() { 
   public void run() { 
    system.out.println("timerone invoked ,the time:" + (system.currenttimemillis() - start)); 
   } 
  }, 3000); 
 } 
  
 public static void main(string[] args) throws exception { 
  timertest04 test = new timertest04(); 
   
  test.timerone(); 
  test.timertwo(); 
 } 
} 

      按照我们正常思路,timertwo应该是在3s后执行,其结果应该是:

timerone invoked ,the time:1001 
timerone invoked ,the time:3001 

      但是事与愿违,timerone由于sleep(4000),休眠了4s,同时timer内部是一个线程,导致timeone所需的时间超过了间隔时间,结果:

timerone invoked ,the time:1000 
timerone invoked ,the time:5000 

 
(2)timer抛出异常缺陷
如果timertask抛出runtimeexception,timer会终止所有任务的运行。如下:

public class timertest04 { 
 private timer timer; 
  
 public timertest04(){ 
  this.timer = new timer(); 
 } 
  
 public void timerone(){ 
  timer.schedule(new timertask() { 
   public void run() { 
    throw new runtimeexception(); 
   } 
  }, 1000); 
 } 
  
 public void timertwo(){ 
  timer.schedule(new timertask() { 
    
   public void run() { 
    system.out.println("我会不会执行呢??"); 
   } 
  }, 1000); 
 } 
  
 public static void main(string[] args) { 
  timertest04 test = new timertest04(); 
  test.timerone(); 
  test.timertwo(); 
 } 
} 

运行结果:timerone抛出异常,导致timertwo任务终止。

exception in thread "timer-0" java.lang.runtimeexception 
 at com.chenssy.timer.timertest04$1.run(timertest04.java:25) 
 at java.util.timerthread.mainloop(timer.java:555) 
 at java.util.timerthread.run(timer.java:505) 

对于timer的缺陷,我们可以考虑 scheduledthreadpoolexecutor 来替代。timer是基于绝对时间的,对系统时间比较敏感,而scheduledthreadpoolexecutor 则是基于相对时间;timer是内部是单一线程,而scheduledthreadpoolexecutor内部是个线程池,所以可以支持多个任务并发执行。
3.2、用scheduledexecutorservice替代timer
(1)解决问题一:

public class scheduledexecutortest { 
 private scheduledexecutorservice scheduexec; 
  
 public long start; 
  
 scheduledexecutortest(){ 
  this.scheduexec = executors.newscheduledthreadpool(2); 
  this.start = system.currenttimemillis(); 
 } 
  
 public void timerone(){ 
  scheduexec.schedule(new runnable() { 
   public void run() { 
    system.out.println("timerone,the time:" + (system.currenttimemillis() - start)); 
    try { 
     thread.sleep(4000); 
    } catch (interruptedexception e) { 
     e.printstacktrace(); 
    } 
   } 
  },1000,timeunit.milliseconds); 
 } 
  
 public void timertwo(){ 
  scheduexec.schedule(new runnable() { 
   public void run() { 
    system.out.println("timertwo,the time:" + (system.currenttimemillis() - start)); 
   } 
  },2000,timeunit.milliseconds); 
 } 
  
 public static void main(string[] args) { 
  scheduledexecutortest test = new scheduledexecutortest(); 
  test.timerone(); 
  test.timertwo(); 
 } 
} 

运行结果:

timerone,the time:1003 
timertwo,the time:2005 

(2)解决问题二

public class scheduledexecutortest { 
 private scheduledexecutorservice scheduexec; 
  
 public long start; 
  
 scheduledexecutortest(){ 
  this.scheduexec = executors.newscheduledthreadpool(2); 
  this.start = system.currenttimemillis(); 
 } 
  
 public void timerone(){ 
  scheduexec.schedule(new runnable() { 
   public void run() { 
    throw new runtimeexception(); 
   } 
  },1000,timeunit.milliseconds); 
 } 
  
 public void timertwo(){ 
  scheduexec.scheduleatfixedrate(new runnable() { 
   public void run() { 
    system.out.println("timertwo invoked ....."); 
   } 
  },2000,500,timeunit.milliseconds); 
 } 
  
 public static void main(string[] args) { 
  scheduledexecutortest test = new scheduledexecutortest(); 
  test.timerone(); 
  test.timertwo(); 
 } 
} 

运行结果:

timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
timertwo invoked ..... 
........................ 


四、使用定时器实现弹弹球
模拟书上的一个例题做了一个弹弹球,是在画布上的指定位置画多个圆,经过一段的延时后,在附近位置重新画。使球看起来是动,通过jspinner组件调节延时,来控制弹弹球的移动速度.
        ballscanvas.java

public class ballscanvas extends canvas implements actionlistener, 
  focuslistener { 
 
 private ball balls[]; // 多个球 
 private timer timer; 
 
 private static class ball { 
  int x, y; // 坐标 
  color color; // 颜色 
  boolean up, left; // 运动方向 
 
  ball(int x, int y, color color) { 
   this.x = x; 
   this.y = y; 
   this.color = color; 
   up = left = false; 
  } 
 } 
 
 public ballscanvas(color colors[], int delay) { // 初始化颜色、延时 
  this.balls = new ball[colors.length]; 
  for (int i = 0, x = 40; i < colors.length; i++, x += 40) { 
   balls[i] = new ball(x, x, colors[i]); 
  } 
  this.addfocuslistener(this); 
  timer = new timer(delay, this); // 创建定时器对象,delay指定延时 
  timer.start(); 
 
 } 
 
 // 设置延时 
 public void setdelay(int delay) { 
  timer.setdelay(delay); 
 } 
 
 // 在canvas上面作画 
 public void paint(graphics g) { 
  for (int i = 0; i < balls.length; i++) { 
   g.setcolor(balls[i].color); // 设置颜色 
   balls[i].x = balls[i].left ? balls[i].x - 10 : balls[i].x + 10; 
   if (balls[i].x < 0 || balls[i].x >= this.getwidth()) { // 到水平方向更改方向 
    balls[i].left = !balls[i].left; 
   } 
 
   balls[i].y = balls[i].up ? balls[i].y - 10 : balls[i].y + 10; 
   if (balls[i].y < 0 || balls[i].y >= this.getheight()) { // 到垂直方向更改方向 
    balls[i].up = !balls[i].up; 
   } 
   g.filloval(balls[i].x, balls[i].y, 20, 20); // 画指定直径的圆 
  } 
 } 
 
 // 定时器定时执行事件 
 @override 
 public void actionperformed(actionevent e) { 
  repaint(); // 重画 
 } 
 
 // 获得焦点 
 @override 
 public void focusgained(focusevent e) { 
  timer.stop(); // 定时器停止 
 
 } 
 
 // 失去焦点 
 @override 
 public void focuslost(focusevent e) { 
  timer.restart(); // 定时器重启动 
 
 } 
} 

ballsjframe.java

class ballsjframe extends jframe implements changelistener { 
 
  private ballscanvas ball; 
  private jspinner spinner; 
 
  public ballsjframe() { 
   super("弹弹球"); 
   this.setbounds(300, 200, 480, 360); 
   this.setdefaultcloseoperation(exit_on_close); 
   color colors[] = { color.red, color.green, color.blue, 
     color.magenta, color.cyan }; 
   ball = new ballscanvas(colors, 100); 
   this.getcontentpane().add(ball); 
 
   jpanel panel = new jpanel(); 
   this.getcontentpane().add(panel, "south"); 
   panel.add(new jlabel("delay")); 
   spinner = new jspinner(); 
   spinner.setvalue(100); 
   panel.add(spinner); 
   spinner.addchangelistener(this); 
   this.setvisible(true); 
  } 
 
  @override 
  public void statechanged(changeevent e) { 
   // 修改jspinner值时,单击jspinner的up或者down按钮时,或者在jspinner中按enter键 
   ball.setdelay(integer.parseint("" + spinner.getvalue())); 
 
  } 
 
 public static void main(string[] args) { 
  new ballsjframe(); 
 } 
 
} 

效果如下:

201622684913936.jpg (469×345)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网