本文共 1496 字,大约阅读时间需要 4 分钟。
一个多线程并发排队
- 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();
- }
-
- 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();
-
- }
-
- 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();
-
- return call;
- }
-
- public int size(){
- return QUEUE.size();
-
- }
-
- public void clear(){
- QUEUE.clear();
- }
-
- public boolean isEmpty(){
- return QUEUE.isEmpty();
- }
-
- private void printQueueSize(){
- System.out.println("Concurrent queue size: "+QUEUE_SIZE);
- }
- }
转载地址:http://wcnmd.baihongyu.com/