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

 一个多线程并发排队
  1. /**
  2.  * 线程请求队列,用来处理多线程并发排队.
  3.  * 实际用的是先进先出的堆栈 Queue,默认队大小为128
  4.  * @author guishuanglin 2008-11-3
  5.  * 
  6.  */
  7. public class ConcurrentQueue {
  8.     private Queue QUEUE;
  9.     private int QUEUE_SIZE = 128;
  10.     private String QUEUE_NAME = "Queue";
  11.     
  12.     public ConcurrentQueue() {
  13.         QUEUE = new Queue();
  14.         printQueueSize();
  15.     }
  16.     public ConcurrentQueue(int size) {
  17.         QUEUE_SIZE = size;
  18.         QUEUE = new Queue();
  19.         printQueueSize();
  20.     }
  21.     public ConcurrentQueue(int size,String name) {
  22.         QUEUE_SIZE = size;
  23.         QUEUE_NAME = QUEUE_NAME+"["+name+"]";
  24.         QUEUE = new Queue();
  25.         printQueueSize();
  26.     }
  27.     /**
  28.      * 入队
  29.      * @param call
  30.      */
  31.     public synchronized void enQueue(Object call) {
  32.         while (QUEUE.size() > QUEUE_SIZE) {
  33.             try {
  34.                 System.out.println(QUEUE_NAME+" wait enQueue....");
  35.                 wait();
  36.             } catch (InterruptedException e) {
  37.                 e.printStackTrace();
  38.             }
  39.         }
  40.         QUEUE.add(call);
  41.         notifyAll();
  42.         //System.out.println("入队");
  43.     }
  44.     /**
  45.      * 出队
  46.      * @param call
  47.      */
  48.     public synchronized Object deQueue() {
  49.         Object call;
  50.         while (QUEUE.isEmpty()) {
  51.             try {
  52.                 System.out.println(QUEUE_NAME+" wait deQueue....");
  53.                 wait();
  54.             } catch (InterruptedException e) {
  55.                 e.printStackTrace();
  56.             }
  57.         }
  58.         call = QUEUE.poll();
  59.         notifyAll();
  60.         //System.out.println("出队");
  61.         return call;
  62.     }
  63.     /**
  64.      * 打印当前队大小
  65.      * @date 2008-11-4
  66.      */
  67.     public int size(){
  68.         return QUEUE.size();
  69.         
  70.     }
  71.     /**
  72.      * 清空队
  73.      * @date 2008-11-4
  74.      */
  75.     public void clear(){
  76.         QUEUE.clear();
  77.     }
  78.     /**
  79.      * 测试队是否有元素
  80.      * @date 2008-11-4
  81.      */
  82.     public boolean isEmpty(){
  83.         return QUEUE.isEmpty();
  84.     }
  85.     /**
  86.      * 打印当前队大小
  87.      * @date 2008-11-4
  88.      */
  89.     private void printQueueSize(){
  90.         System.out.println("Concurrent queue size: "+QUEUE_SIZE);
  91.     }
  92. }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值