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. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章