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:
- Call fire()explicitly on the timer instance to see if you can force things
- Try creating your handler by passing in the logic as a Runnableobject 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;                  
    }
  });
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论