使用 java 库信号量的有界缓冲区

Bounded-buffer using java library semaphore

我目前有一个任务,我应该为有界缓冲区问题制作一个信号量。我认为我的第一个代码没问题并且应该可以工作(如果我正确理解信号量,顺便说一句我不确定)

作业的第二部分是使用java 库来实现信号量。我这样做对吗? 我为作业的每个部分都提供了两个代码块。我只需要验证我的代码是否正确,也许还有一些关于使用 java 信号量库的输入:)

semaphore mutex = 1;
semaphore fillCount = 0;
semaphore emptyCount = BUFFER_SIZE;

procedure producer() {
  while (true) {
    item = produceItem();       
    down(emptyCount);       
        down(mutex);            
            putItemIntoBuffer(item);    
        up(mutex);          
    up(fillCount);      
}
}

procedure consumer() {
while (true) {
    down(fillCount);                
        down(mutex);                
            item = removeItemFromBuffer();  
        up(mutex);              
    up(emptyCount);             
    consumeItem(item);      
}
}

使用Java-信号量:

 Semaphore semaphore = new Semaphore(1);

public producer(){     

semaphore.acquire();  
    putItemIntoBuffer(item);  
semaphore.release(); 

}

public consumer(){
semaphore.acquire();

removeItemFromBuffer(item);   

semaphore.release();
 }

在您的第一个代码示例中,您使用了二进制信号量和计数信号量。您也应该在 java 实施中使用它。 我认为,你应该用 0 初始化信号量(用于产品计数)。 当你使用 1 时,你可以从你的缓冲区中取出一个项目,当它仍然是空的时候。

Semaphore mutex = new Semaphore(1);
Semaphore productCount = new Semaphre(0);

public producer(){     

mutex.acquire();  //entering critical section
    putItemIntoBuffer(item); //produce your item in the exclusive mode
    productCount.release();  //increase your product count
mutex.release();  //leave critical section

}

public consumer(){
mutex.acquire(); //entering critical section

if(productCount.availablePermits() > 0) //test if you have already poduced some items
{
   removeItemFromBuffer(item); //remove your item in the exclusive mode  
   productCount.acquire();     //decrease your item count
}

mutex.release(); //leave critical section
 }

使用锁和条件对象

class BoundedBuffer {
   final Lock lock = new ReentrantLock();
   final Condition notFull  = lock.newCondition(); 
   final Condition notEmpty = lock.newCondition(); 

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length)
         notFull.await();
       items[putptr] = x;
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0)
         notEmpty.await();
       Object x = items[takeptr];
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   }
 }