import java.util.Vector; /*** * 雙緩衝消息隊列 * @author Donald * */ public class MessageQueueThread extends Thread { public int capacity=50; public boolean autoIncrement=false; private Vector readQueue=new Vector(capacity); private Vector writeQueue=new Vector(capacity); // private Object readLock=new Object(); private Object writeLock=new Object(); private MessageHandler handler; public void run(){ if(handler==null) return; Message msg=null; while (true) { if (!readQueue.isEmpty()) { msg=(Message) readQueue.firstElement(); readQueue.removeElement(msg); if(msg!=null) handler.onReceive(msg); msg=null; } else { synchronized (writeLock) { if (!writeQueue.isEmpty()) { readQueue =writeQueue; writeQueue=null; writeQueue=new Vector(capacity); } } System.gc(); } try { Thread.sleep(10); } catch (InterruptedException e) { } } } public void sendMessage(Message msg){ synchronized (writeLock) { if(writeQueue.size()<capacity||autoIncrement){ writeQueue.addElement(msg); } } } public void setHandler(MessageHandler handler) { this.handler = handler; } public MessageHandler getHandler() { return handler; } public static class Message{ public int what; public Object data; public Message(int what,Object data){ this.what=what; this.data=data; } } public interface MessageHandler{ public void onReceive(Message msg); } }