Analysis of timers in Java and the use of timer to make a pinball game example _java

Source: Internet
Author: User
Tags static class

In our programming process, if we need to perform some simple timing tasks, no complex control, we can consider using the JDK Timer task to achieve. The following LZ on its principles, examples and timer defects three aspects to resolve the Java timer timer.

First, Introduction
In Java, a full timed task needs to be done with timer, timertask two classes. The API defines them, Timer: A tool that the thread uses to schedule tasks to be performed later in the background thread. You can schedule tasks to execute once, or repeat them periodically. A task that is scheduled for execution or repeated by Timertask:timer. We can understand that. Timer is a timer tool that is used to schedule a specified task in a background thread, and timertask an abstract class that represents a task that can be scheduled by a timer.
Timer class
In the tool class timer, four construction methods are provided, each of which starts a timer thread, and the timer class guarantees that multiple threads can share a single Timer object without external synchronization, so the timer class is thread safe. But because each timer object corresponds to a single background thread, used for sequential execution of all timer tasks, our thread task execution normally takes a very short time, but because of special circumstances that cause a timer task to execute too long, he will "monopolize" the task execution thread of the timer , all subsequent threads must wait for it to finish, which will delay the execution of the successor tasks, piling these tasks together, as we analyze later.
When the program initializes the timer, the timed task is executed at the time we set, and the timer provides the schedule method, which is overloaded in many ways to accommodate different situations, as follows:
Schedule (timertask task, Date time): Schedule the specified task at the specified times.
Schedule (timertask task, Date Firsttime, long period): schedules the specified task to begin repeating fixed-delay execution at a specified time.
Schedule (timertask task, long delay): Schedules the specified task after the specified delay.
Schedule (timertask task, long delay, long period): schedules the specified task to begin repeating fixed-delay execution from the specified delay.
At the same time, the Scheduleatfixedrate method is overloaded, and the Scheduleatfixedrate method is the same as that of schedule, except that their emphasis is different and the following analysis is distinguished.
Scheduleatfixedrate (timertask task, Date Firsttime, long period): schedules the specified task to start at a specified time for repeated fixed-rate execution.
Scheduleatfixedrate (timertask task, long delay, long period): schedules the specified task to begin repeating fixed-rate execution after the specified delay.
TimerTask
The TimerTask class is an abstract class that is scheduled by a timer for a task that is executed or repeated at one time. It has an abstract method run () method that performs the action to be performed by the corresponding timer task. Therefore, each specific task class must inherit TimerTask and then rewrite the run () method.
In addition, it has two non-abstract methods:
Boolean cancel (): Cancels this timer task.
Long Scheduledexecutiontime (): Returns the scheduled execution time of the most recent actual execution of this task.

Second, the example
2.1. Specify the delay time to perform scheduled tasks

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!!!!"); 
 } 
} 

Run Result:

Print First:

Timer begin .... 


Print after 3 seconds:

Time ' s up!!!! 

2.2. Perform scheduled tasks at specified times

public class TimerTest02 { 
 timer timer; 
  
 Public TimerTest02 () { 
  Date time = GetTime (); 
  System.out.println ("Specify Time Time=" + times); 
  Timer = new timer (); 
  Timer.schedule (New TimerTaskTest02 (), time); 
  
 Public Date GetTime () { 
  Calendar calendar = calendar.getinstance (); 
  Calendar.set (Calendar.hour_of_day, one); 
  Calendar.set (Calendar.minute,); 
  Calendar.set (Calendar.second); 
  Date time = Calendar.gettime (); 
   
  return time; 
 } 
  
 public static void Main (string[] args) { 
  new TimerTest02 (); 
 } 
} 
 
The public class TimerTaskTest02 extends timertask{ 
 
 @Override 
 the public void Run () { 
  System.out.println (" Specify time to perform thread task ... "); 
 } 
 

When the time arrives 11:39:00, the thread task is executed, and of course it will be executed more than that time!! The results of the execution are:

Specified time Time=tue June 11:39:00 CST 2014 
specify time to perform thread tasks ... 

2.3. Cycle the timed task at a specified interval after a specified time delay

public class TimerTest03 { 
 timer timer; 
  
 Public TimerTest03 () { 
  timer = new timer (); 
  Timer.schedule (New TimerTaskTest03 (), 1000, Watts); 
  
 public static void Main (string[] args) { 
  new TimerTest03 (); 
 } 
} 
 
public class TimerTaskTest03 extends timertask{ 
 
 @Override the public 
 Void Run () { 
  date = new Date (This.sc Heduledexecutiontime ()); 
  System.out.println ("The time of this execution of this thread is:" + date); 
 } 
 

Run Result:

The time this thread was executed was: Tue June 21:19:47 CST 2014 the 
time this thread was executed was: Tue June 21:19:49 CST 2014 
This thread was executed at this time: Tue June 10 21:19:51  CST 2014 The 
time this thread was executed: Tue June 21:19:53 CST 2014 the time this 
thread was executed was: Tue June 21:19:55 CST 2014 the 
time this thread was executed was: Tue June 21:19:57 CST 2014 ........... 
 

For this thread task, if we do not stop the task, he will continue to run.
For the above three examples, LZ is just a simple demo, at the same time did not explain the Scheduleatfixedrate method of example, in fact, the method and the Schedule Method!
2.4. Analysis of schedule and Scheduleatfixedrate
(1) Schedule (timertask task, Date time), schedule (timertask task, long delay)
For both methods, if the specified schedule execution time scheduledexecutiontime<= Systemcurrenttime, the task is executed immediately. Scheduledexecutiontime will not change because of the excessive execution of a task.
(2) Schedule (timertask task, Date Firsttime, long period), schedule (timertask task, long delay, long period)
These two methods are a little different from the top two, and the timer task that preceded the timer will be delayed because the previous task performed longer. In both methods, the scheduled time for each task executed changes with the actual time of the previous task, i.e. Scheduledexecutiontime (n+1) =realexecutiontime (n) +periodtime. That is, if the nth task causes this execution time process in some way, it eventually leads to systemcurrenttime>= Scheduledexecutiontime (n+1), which is the n+1 task and is not executed because of the time. He waits for the nth task to execute after execution, so it is bound to cause the execution of n+2 to implement Scheduledexecutiontime release change that is Scheduledexecutiontime (n+2) = Realexecutiontime (n+1) +periodtime. So these two methods pay more attention to the stability of the storage interval time.
(3) Scheduleatfixedrate (timertask task, Date Firsttime, long period), Scheduleatfixedrate (timertask task, long delay, Long period)
As mentioned above, the emphasis of scheduleatfixedrate and schedule method is different, the schedule method focuses on the stabilization of interval time, and the Scheduleatfixedrate method is more focused on keeping the execution frequency stable. Why do you say that, for the following reasons. In the schedule method, the delay of the previous task results in a delayed scheduled task, and the Scheduleatfixedrate method does not, if the nth task executes too long, causing systemcurrenttime>= Scheduledexecutiontime (n+1) will not do any wait he will immediately execute the first n+1 task, so the method of executing the Scheduleatfixedrate method differs from that of schedule, Instead of Scheduledexecutiontime (n) =firstexecutetime +n*periodtime, the calculation method remains unchanged forever. So Scheduleatfixedrate is more focused on keeping the execution frequency stable.

Third, the timer's flaw
3.1, Timer's flaw
The timer timer can be timed (to perform a task at a specified time), delay (delay 5 seconds to perform a task), perform tasks periodically (perform tasks every 1 seconds), but there are some drawbacks to the timer. First, the timer's support for scheduling is based on absolute time, not relative time, so it's very sensitive to changes in system time. Second, the timer thread does not catch exceptions, and if the unchecked exception thrown by TimerTask causes the timer thread to terminate and the timer does not restore the execution of the thread, he will mistakenly assume that the entire timer thread will be canceled. At the same time, TimerTask, which has already been scheduled for a single execution, will not be executed, and new tasks cannot be scheduled. So if the timertask throws an unchecked exception, the timer will produce unpredictable behavior.
(1) Timer management time delay defects
The previous timer creates only one thread task when it performs a scheduled task, and if there are multiple threads, some defects occur if one of the threads causes the thread task to execute too long for some reason, exceeding the interval of two tasks:

public class TimerTest04 { 
 private timer timer; 
 public long start;  
  
 Public TimerTest04 () { 
  This.timer = new timer (); 
  Start = System.currenttimemillis (); 
 } 
  
 The public void Timerone () {timer.schedule () { 
  the new TimerTask () {public 
   void run () { 
    System.out.println () Timerone invoked, the time: "+ (System.currenttimemillis ()-start)"; 
    try { 
     thread.sleep (4000);//thread Hibernate 3000 
    } catch (Interruptedexception e) { 
     e.printstacktrace (); 
    } 
   } 
  }, 1000); 
  
 The public void Timertwo () {timer.schedule () { 
  the 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 (); 
 } 
 

According to our normal thinking, the timertwo should be executed after 3s, and the result should be:

Timerone invoked, the time:1001 
Timerone invoked, the time:3001 

But it backfired, Timerone due to sleep (4000), dormant 4s, while the timer inside is a thread, resulting in timeone required more time than the interval, the result:

Timerone invoked, the time:1000 
Timerone invoked, the time:5000 


(2) Timer throws abnormal defect
If TimerTask throws Runtimeexception,timer, all tasks are terminated. As follows:

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 (); c9/>} 
  }, 1000); 
  
 The public void Timertwo () {timer.schedule () { 
  the new TimerTask () {public 
    
   void run () { 
    System.out.println () Will I do it?? ");}} 
  , 1000); 
  
 public static void Main (string[] args) { 
  TimerTest04 test = new TimerTest04 (); 
  Test.timerone (); 
  Test.timertwo (); 
 } 
 

Run Result: Timerone throws an exception, causing the Timertwo task to terminate.

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) 

For timer defects, we can consider scheduledthreadpoolexecutor instead. Timer is based on absolute time, more sensitive to system time, and Scheduledthreadpoolexecutor is based on relative time; timer is a single thread inside, and Scheduledthreadpoolexecutor is a thread pool inside , so multiple tasks can be supported for concurrent execution.
3.2, replace timer with Scheduledexecutorservice
(1) Solve problem one:

 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 ("Ti 
    Merone,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 ("Ti 
   Mertwo,the Time: "+ (System.currenttimemillis ()-start);" 
 }},2000,timeunit.milliseconds); 
  public static void Main (string[] args) {scheduledexecutortest test = new Scheduledexecutortest (); 
  Test.timerone (); 
 Test.timertwo (); } 
} 

Run Result:

Timerone,the time:1003 
timertwo,the time:2005 

(2) solve the problem two

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 (); 
 } 
 

Run Result:

Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... Timertwo invoked 
... ........................ 


Four, the use of timer to achieve the pinball ball
An example in a mock book is a pinball that draws a plurality of circles at a specified position on the canvas, after a period of delay, and redraw in a nearby position. The ball appears to be moving, adjusting the delay through the Jspinner component to control the moving speed of the projectile ball.
Ballscanvas.java

public class Ballscanvas extends Canvas implements ActionListener, Focuslistener {private Ball balls[];//Multiple Balls 
 
 private timer timer; private static class Ball {int x, y;//coordinates color color;//color Boolean up, left;//motion Direction 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) {//Initialize color, delay this.balls = new Ball[colors.length]; 
  for (int i = 0, x = i < colors.length i++, X + +) {Balls[i] = new Ball (x, X, colors[i)); 
  } this.addfocuslistener (this); Timer = new Timer (delay, this); 
 
 Create timer object, delay specify delay Timer.start (); 
 //Set delay public void setdelay (int delay) {timer.setdelay (delay); ///paint on canvas public void paint (Graphics g) {for (int i = 0; i < balls.length; i++) {G.setcolor [I].color); Set 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 ()) {//to the horizontal direction change direction 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 ()) {//to Vertical direction change direction balls[i].up =!balls[i].up; } g.filloval (balls[i].x, Balls[i].y, 20, 20); 
 
 Draw the specified diameter of the circle}//Timer timed to execute event @Override public void actionperformed (ActionEvent e) {repaint ();//repaint} 
 Get focus @Override public void focusgained (FocusEvent e) {timer.stop ();//Timer Stop}//Lose Focus @Override 

 public void Focuslost (FocusEvent e) {timer.restart ();//Timer reboot}}

Ballsjframe.java

 class Ballsjframe extends JFrame implements ChangeListener {private Ballscanvas ball; 
 
  Private JSpinner spinner; 
   Public Ballsjframe () {super ("Bouncing Ball"); 
   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) {//Modify Jspinner value, click Jspinner up or Down button, or press Jspinner in Ente 
 
  R Key Ball.setdelay (Integer.parseint ("" + Spinner.getvalue ())); 
 public static void Main (string[] args) {new ballsjframe (); } 
 
} 

The effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.