记录型信号量解决消费者-生产者问题

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&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值