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

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<100;++i){
			producerAndConsumer.new Consumer(caches).start();
		}
		
		for(int i=0;i<100;++i){
			producerAndConsumer.new Producer(caches).start();
		}
	
	}


	/**
	 * 生产者
	 *
	 */
	class Producer extends Thread{
		Cache[] caches;
		public Producer(Cache[] caches){
			this.caches=caches;
		}
		private void createProduct(){
			//System.out.println("生产者"+getId()+"执行中");
			waitS(empty);
			waitS(mutex);
			
			caches[in].in();
			in=(in+1)%cacheSize;
			signalS(mutex);
			signalS(full);
			//System.out.println("生产者"+getId()+"执行完 in="+in);
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			createProduct();
		}
	}
	
	/**
	 * 消费者
	 *
	 */
	class Consumer extends Thread{
		Cache[] caches;
		public Consumer(Cache[] caches){
			this.caches=caches;
		}
		private void consumeProduct(){
			//System.out.print("消费者"+getId()+"执行中");
			waitS(full);
			waitS(mutex);
			
			
			caches[out].out();
			out=(out+1)%cacheSize;
			signalS(mutex);
			signalS(empty);
			//System.out.print("消费者"+getId()+"执行完");
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			consumeProduct();
		}
	}
	
	/**
	 * 缓冲区
	 *
	 */
	class Cache{
		//缓冲区编号
		private int cacheNumber;
		public int getCacheNumber() {
			return cacheNumber;
		}
		public void setCacheNumber(int cacheNumber) {
			this.cacheNumber = cacheNumber;
		}
		public void in(){
			System.out.println(cacheNumber+" 号缓冲区已填充");
		}
		public void out(){
			System.out.println(cacheNumber+" 号缓冲区已取出");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值