日期:2014-05-20  浏览次数:20809 次

java多线程消息通信问题
两个线程共同操作一个固定大小的数组缓冲区,一个向里面放入数据,另外一个从里面读取数。
不知道是不是,应该是单对单的生产者-消费者模型
代码中不使用同步,单一写,单一读,如图

直接上代码了~ 求高人指点~

package graph.utils;
import java.util.Iterator;
import java.util.NoSuchElementException;


public class FixedRingBuffer<Item> implements Iterable<Item> {
    private Item[] q;            // queue elements
    private int N = 0;           // number of elements on queue
    private int first = 0;       // index of first element of queue
    private int last  = 0;       // index of next available slot

    /**
     * Initializes an empty queue.
     */
    public FixedRingBuffer() {
        // cast needed since no generic array creation in Java
     this(2);
    }
    
    public FixedRingBuffer(int capacity){
     q = (Item[]) new Object[capacity];
    }

    /**
     * Is this queue empty?
     * @return true if this queue is empty; false otherwise
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * Returns the number of items in this queue.
     * @return the number of items in this queue
     */
    public int size() {
        return N;
    }
    
    public boolean hasCapacity(){
     return !(N == q.length);
    }

    /**
     * Adds the item to this queue.
     * @param item the item to add
     */
    public void enqueue(Item item) {
     if(!hasCapacity()) throw new ArrayIndexOutOfBoundsException("not enough room for the item"); 
        q[last++] = item;                        // add item
        if (last == q.length) last = 0;          // wrap-around
        N++;
    }

   
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = q[first];
        q[first] = null;                            // to avoid loitering
        N--;
        first++;
        if (first == q.length) first = 0;           // wrap-around
        // shrink size of array if necessary
        //if (N > 0 && N == q.length/4) resize(q.length/2); 
        return item;
    }

    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        return q[first];
    }


    /**
     * Returns an iterator that iterates over the items in this queue in FIFO order.
     * @return an iterator that iterates over the items in this queue in FIFO order