您的位置:首页 > 编程语言 > Java开发

jdk1.4 构建 java多线程,并发设计框架 (二)

2008-12-06 09:56 726 查看
 一个多线程并发排队
/**
 * 线程请求队列,用来处理多线程并发排队.
 * 实际用的是先进先出的堆栈 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);
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: