- /**
- * 線程請求隊列,用來處理多線程併發排隊.
- * 實際用的是先進先出的堆棧 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);
- }
- }
jdk1.4 構建 java多線程,併發設計框架 (二)
一個多線程併發排隊
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.