使用信号量的生产者消费者有界缓冲区

Producer Consumer bounded buffer using Semaphore

下面是我对PC问题的实现

public class CircularQueue {
Queue <Integer>queue = new LinkedList<Integer>();
final int LIMIT = 10;
static Semaphore semProd = new Semaphore(1);
static Semaphore semConsu = new Semaphore(0);
public void enqueue(int productId) throws InterruptedException{

        semProd.acquire();
         queue.add(productId);
         System.out.println(Thread.currentThread().getName()+" Putting(In Q) Product ID:"+productId);
         semConsu.release();
}

public int deueue() throws InterruptedException{
        semConsu.acquire();
        int productID = (int) queue.remove();
        System.out.println(Thread.currentThread().getName()+" Getting (In Q) Product ID:"+productID);
        semProd.release();
    return productID;
}
}



//producer class
public class Producer implements Runnable{
CircularQueue cQueue ;
public Producer(CircularQueue queue){
    this.cQueue = queue;

}

public void run(){
    while(true){
    for(int i =0 ; i < 5 ;i++){

        try {
            cQueue.enqueue(i);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    }}}


//consumer class
public class Consumer implements Runnable{

CircularQueue cQueue ;
public Consumer(CircularQueue cQueue){
    this.cQueue = cQueue;

}
public void run(){

    try {
        while(true){
        int item = cQueue.deueue();
        Thread.sleep(2000);}
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}}


//Driver Class
public class DriverClass {

public static void main(String args[]){

    CircularQueue cQueue = new CircularQueue();
    new Thread(new Producer(cQueue)).start();
    new Thread(new Consumer(cQueue)).start();


}}

1) 如何检查我的实现是否正确 2)如果我想为多个消费者和多个生产者编辑解决方案,那么我应该如何更改实现

增加 semProduce 和 sem 消耗的数量是否足够?

static Semaphore semProd = new Semaphore(4);//4 producer
static Semaphore semConsu = new Semaphore(3);//3 consumer

对于通用的、有界的、multi-producer/consumer 带有信号量的阻塞队列,您需要三个。一个用于计算队列中可用空间的数量,(初始化为队列的 LIMIT),一个用于计算队列中的项目数量,(初始化为零),另一个用于保护队列免受多重访问,(初始化为 1,充当互斥量)。

伪代码:

生产者:等待(免费);等待(互斥锁); queue.push(新项目);发送(互斥锁);发送(项目);

消费者:等待(物品);等待(互斥量);结果=(queue.pop);发送(互斥锁);发送(免费); return 结果;