生产者消费者使用信号量限制缓冲区

时间:2015-04-03 05:51:23

标签: java multithreading operating-system semaphore producer-consumer

以下是我对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

1 个答案:

答案 0 :(得分:2)

对于具有信号量的通用,有界,多生产者/消费者阻塞队列,您需要其中三个。一个计算队列中的空闲空间数(初始化为队列的LIMIT),一个用于计算队列中的项目数(初始化为零),另一个用于保护队列免受多次访问(初始化为1,充当互斥锁)。

伪代码:

制片人:等待(免费);等待(互斥); queue.push(的newitem);发送(互斥);发送(项目);

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