import java.util.concurrent.Semaphore;
public class ProducerAndConsumer {
//缓冲区数量
private static final int cacheSize=100;
//互斥信号量,用于实现对缓冲区的互斥访问
private Semaphore mutex=new Semaphore(1);
//空缓冲区数量
private Semaphore empty=new Semaphore(cacheSize);
//满缓冲区数量
private Semaphore full=new Semaphore(0);
//当前生产或消费的编号
int in=0,out=0;
public int waitS(Semaphore semaphore){
try {
semaphore.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return semaphore.availablePermits();
}
public int signalS(Semaphore semaphore){
semaphore.release();
return semaphore.availablePermits();
}
public static void main(String[] args) {
ProducerAndConsumer producerAndConsumer=new ProducerAndConsumer();
Cache[] caches=new Cache[cacheSize];
//初始化缓冲区
for(int i=0;i<cacheSize;++i){
caches[i]=producerAndConsumer.new Cache();
caches[i].setCacheNumber(i);
}
for(int i=0;i&
记录型信号量解决消费者-生产者问题
最新推荐文章于 2024-05-12 21:15:28 发布