1 22 23 package common; 24 25 import java.util.LinkedList ; 26 27 28 38 39 public class MessageQueue implements Runnable { 40 private static final int MAX_SIZE = 15; 41 private LinkedList queue; 42 private SocketConnection writer; 43 private boolean running; 44 private boolean empty; 45 46 public MessageQueue(SocketConnection w) { 47 writer = w; 48 queue = new LinkedList (); 49 running = true; 50 empty = true; 51 new Thread (this).start(); 52 } 53 54 synchronized public boolean enqueue(Object obj) { 55 queue.addLast(obj); 56 if (empty) { 57 empty = false; 58 notify(); 59 } 60 if (queue.size() > MAX_SIZE) { 61 writer.close(); 62 } 63 return true; 64 } 65 66 public void run() { 67 while (running) { 68 try { 69 if (queue.size() != 0) { 70 writer._writeObject(queue.removeFirst()); 71 } else { 72 empty = true; 73 synchronized(this) { 74 while (empty) { 75 wait(); 76 } 77 } 78 } 79 Thread.sleep(10); 80 } catch ( InterruptedException inte ) { 81 running = false; 82 } 83 } 84 } 85 } 86 | Popular Tags |