一个多线程并发排队
- /**
- * 线程请求队列,用来处理多线程并发排队.
- * 实际用的是先进先出的堆栈 Queue,默认队大小为128
- * @author guishuanglin 2008-11-3
- *
- */
- public class ConcurrentQueue {
- private Queue QUEUE;
- private int QUEUE_SIZE = 128;
- private String QUEUE_NAME = "Queue";
- public ConcurrentQueue() {
- QUEUE = new Queue();
- printQueueSize();
- }
- public ConcurrentQueue(int size) {
- QUEUE_SIZE = size;
- QUEUE = new Queue();
- printQueueSize();
- }
- public ConcurrentQueue(int size,String name) {
- QUEUE_SIZE = size;
- QUEUE_NAME = QUEUE_NAME+"["+name+"]";
- QUEUE = new Queue();
- printQueueSize();
- }
- /**
- * 入队
- * @param call
- */
- public synchronized void enQueue(Object call) {
- while (QUEUE.size() > QUEUE_SIZE) {
- try {
- System.out.println(QUEUE_NAME+" wait enQueue....");
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- QUEUE.add(call);
- notifyAll();
- //System.out.println("入队");
- }
- /**
- * 出队
- * @param call
- */
- public synchronized Object deQueue() {
- Object call;
- while (QUEUE.isEmpty()) {
- try {
- System.out.println(QUEUE_NAME+" wait deQueue....");
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- call = QUEUE.poll();
- notifyAll();
- //System.out.println("出队");
- return call;
- }
- /**
- * 打印当前队大小
- * @date 2008-11-4
- */
- public int size(){
- return QUEUE.size();
- }
- /**
- * 清空队
- * @date 2008-11-4
- */
- public void clear(){
- QUEUE.clear();
- }
- /**
- * 测试队是否有元素
- * @date 2008-11-4
- */
- public boolean isEmpty(){
- return QUEUE.isEmpty();
- }
- /**
- * 打印当前队大小
- * @date 2008-11-4
- */
- private void printQueueSize(){
- System.out.println("Concurrent queue size: "+QUEUE_SIZE);
- }
- }
本文介绍了一个基于先进先出(FIFO)原则的多线程并发排队机制实现。该机制使用队列结构来管理线程请求,支持动态调整队列大小,并通过同步方法确保线程安全。
257





