使用jdk實現事件模型的經典樣例

 經典的java事件模型

在看sun的代碼時有許多經典實現,非常值得學習,下面是sun事件處理的經典實現,具體看代碼:

public class MainLoop {
 
 private static MainLoop loop=null;
 
 private int pollRequests = 0;
 
 
    private MainLoop(){}

    public static MainLoop getInstance(){
  if(loop==null){
   loop=new MainLoop();
  }
  return loop;
 }
        //自己實現
 public BaseEvent retrieveEvent() {
  return null;
 }
        //自己實現
 private boolean checkEvents() {
  return false;
 }
 
 public synchronized void startPolling() {
  pollRequests++;
  PollingThread.pollingThreadResume();
 }

 public synchronized void stopPolling() {
  pollRequests--;
  if (pollRequests > 0) {
   return;
  }
  PollingThread.pollingThreadSuspend();
 }

 public void pollEvents() {
  while (checkEvents()) {
   BaseEvent event = retrieveEvent();
   if (event != null) {
    event.dispatch();
   }
  }
 }
}


 

mainloop爲主控制類,想讀取事件時,執行startPolling ,會開啓一個pollingThread不停地pollEvent。

pollEvent不停地checkEvent,如果check到,就retrieveEvent,並把得到的event dispatch。

dispatch事件會把事件加入一隊列等待執行事件的process。不想讀事件時,直接stopPolling。需要自己根據情況

實現checkEvent和retrieveEvent,並實現自己的Event繼承自BaseEvent。

BaseEvent.java

public abstract class BaseEvent {
  public void dispatch() {
         Dispatcher.enqueue(this);
     }

     abstract public void process();
}


 

 PollingThread.java

public class PollingThread extends Thread {

 private static PollingThread instance = new PollingThread();

 private static boolean suspended = true;

 private final int POLL_INTERVAL = 1000;

 public PollingThread() {
 }

 public static void pollingThreadSuspend() {
  synchronized (instance) {
   suspended = true;
  }
 }

 public static void pollingThreadResume() {
  try {
   instance.start();
  } catch (IllegalThreadStateException e) {
  }
  synchronized (instance) {
   suspended = false;
   instance.notify();
  }
 }


 public void run() {
  MainLoop loop = MainLoop.getInstance();
  while (true) {
   try {
    synchronized (this) {
     if (suspended) {
      wait();
     }
    }
    loop.pollEvents();
    synchronized (this) {
     wait(POLL_INTERVAL);
    }
   } catch (InterruptedException e) {
    break;
   }
  }
 }
}

 

Dispatcher.java

public class Dispatcher extends Thread {

 private static Dispatcher instance = new Dispatcher();

 private static Vector<BaseEvent> events = new Vector<BaseEvent>();

 public Dispatcher() {
 }


 public static void enqueue(BaseEvent event) {
  try {
   instance.start();
  } catch (IllegalThreadStateException e) {
  }
  synchronized (events) {
   events.addElement(event);
   events.notify();
  }
 }

 public void run() {
  while (true) {
   BaseEvent event = null;
   synchronized (events) {
    if (!events.isEmpty()) {
     event =events.firstElement();
     events.removeElementAt(0);
    } else {
     try {
      events.wait();
     } catch (InterruptedException e) {
      break;
     }
    }
   }
   if (event != null) {
    event.process();
   }
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章