Subversion Repositories HomeAutomation

Rev

Go to most recent revision | Blame | Last modification | View Log | SVN | RSS feed

  1. /*
  2.  * MbPacketQueueHandler.java
  3.  *
  4.  * Created on den 24 augusti 2003, 15:11
  5.  */
  6. package Macbeth.System;
  7.  
  8. /**
  9.  * A packet queue handler, which pulls packets from a packet
  10.  * queue, and handles over each pulled packet to a packet handler
  11.  * object.
  12.  * @author Jimmy
  13.  */
  14. public class MbPacketQueueHandler extends Thread {
  15.     private MbPacketHandler packetHandler;
  16.     private MbPacketQueue packetQueue;
  17.     private boolean runThread;
  18.  
  19.     /**
  20.      * Creates a new instance of MbPacketQueueHandler.
  21.      * @param packetqueue The packet queue to handle.
  22.      * @param packethandler The packet handler that should be
  23.      * invoked when packets need to be handled.
  24.      */
  25.     public MbPacketQueueHandler(MbPacketQueue packetqueue, MbPacketHandler packethandler) {
  26.         super("MbPacketQueueHandler");
  27.         packetQueue = packetqueue;
  28.         packetHandler = packethandler;
  29.     }
  30.  
  31.     /**
  32.      * Start working with the queue.
  33.      */
  34.     public void startWorking() {
  35.         runThread = true;
  36.         //start thread (it will call our run-method in a new thread)
  37.         start();
  38.     }
  39.  
  40.     /**
  41.      * Stop working with the queue.
  42.      */
  43.     public void stopWorking() {
  44.         runThread = false;
  45.     }
  46.  
  47.     /**
  48.      * This is called by the thread when running.
  49.      */
  50.     public void run() {
  51.         //loop while run-flag is set true
  52.         while (runThread) {
  53.             //if there are packets in the queue and packet handler is ready
  54.             if (packetQueue.getSize()>0 && packetHandler.canHandlePacket()) {
  55.                 //pull packet from head of the queue and tell the packet handler to handle it
  56.                 packetHandler.handlePacket(packetQueue.dequeue());
  57.             } else {
  58.                 //if queue is empty of packet handler not ready yet, try to get some sleep=)
  59.                 try {
  60.                     sleep(5);
  61.                 } catch (InterruptedException e) {
  62.                     //don't care
  63.                 }
  64.             }
  65.         }
  66.     }
  67. }
  68.