Semaphore生产者消费者

import java.util.concurrent.Semaphore;
/*Semaphore 生产消费
 *  http://blog.itpub.net/30024515/viewspace-1429123/
 * https://blog.csdn.net/qq_24489717/article/details/70147789
 * 
 * */
public class ProducerConsumerProblem{

	//初始容量
	private static final int N = 10;

	/***
	 * full 产品容量
	 * empty 空余容量
	 * mutex 读写锁
	 */
	private static Semaphore full,empty,mutex;
	//记录当前的产品数量
	private static volatile int count = 0 ;

	static {
		/**
		 * full 初始化0个产品
		 * empty 初始化有N个空余位置放置产品
		 * mutex 初始化每次最多只有一个线程可以读写
		 * */
		full = new Semaphore(0);
		empty = new Semaphore(N);
		mutex = new Semaphore(1);
	}


	public static void main(String []args){
		//生产线线程
		new Thread(new Producer()).start();
		//消费者线程
		new Thread(new Consumer()).start();
	}

	//生产者类
	static class Producer implements Runnable{

		@Override
		public void run() {
			while (true){
				try {
					
					empty.acquire();//等待空位              
					mutex.acquire();//等待读写锁                      
					count++;
					System.out.println("生产者生产了一个,还剩:"+count);
					mutex.release();//释放读写锁
					full.release();//放置产品
					//随机休息一段时间,让生产者线程有机会抢占读写锁
					// Thread.sleep(((int)Math.random())%10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	//消费者类
	static class Consumer implements Runnable{

		@Override
		public void run() {
			while (true){
				try {
					full.acquire();//等待产品
					mutex.acquire();//等待读写锁
					count--;
					System.out.println("消费者消费了一个,还剩:"+count);
					mutex.release();//释放读写锁
					empty.release();//释放空位
					//随机休息一段时间,让消费者线程有机会抢占读写锁
					// Thread.sleep(((int)Math.random())%10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

http://blog.itpub.net/30024515/viewspace-1429123/

https://blog.csdn.net/qq_24489717/article/details/70147789

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值