开发者

Real time java - async event handler fails to fire

The following code is adapted from an example in Real-Time Java Platform Programming by Peter C. Dibble:

import javax.realtime.*;
public class OSTimer {

  static volatile boolean cont = true;

  public static void main(String[] args) {
    AsyncEventHandler handler = new AsyncEventHandler(){
        public void handleAsyncEvent() {
          System.out.println("Stopping...");
          cont = false;                  
        }
      }
    };

   OneShotTimer timer = new OneShotTimer(new RelativeTime(3000, 0), handler);
   timer.start();

   while(cont){
    开发者_StackOverflow System.out.println("Running");
     if (timer.isRunning()) System.out.println("Timer is running");
     try {
       Thread.sleep(1000);
     } catch(Exception e) { }
   }
   System.exit(0);
}

The the program is supposed to run for 3 seconds and then exit. However, the output shows that while the timer did indeed stop after 3 seconds, the program continues as usual, i.e. output is:

Running
Timer is running
Running
Timer is running
Running
Timer is running
Running
Running
Running......

Clearly the handler did not fire, and I've no idea why. Another example program involving a periodic timer triggering the handler does work as expected. The program structure is almost the same as the one here.


A few things to try:

  1. Call fire() explicitly on the timer instance to see if you can force things
  2. Try creating your handler by passing in the logic as a Runnable object to the handler. The API is a little unclear on this, but this is how I have specified handlers in the past.

Example:

AsyncEventHandler handler = new AsyncEventHandler(new Runnable() {
    public void run() {
      System.out.println("Stopping...");
      cont = false;                  
    }
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜