基于java信号量Semaphore实现生产者消费者逻辑


import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Test{
	private int size = 10;
    /**
     * 空位的信号量  初始全空      
     */
	private Semaphore empty = new Semaphore(size);
	/**
	 * 有的信号量  初始什么都没有
	 */
	private Semaphore full = new Semaphore(0);
	/**
	 * 承载的容器   
	 */
	private Integer[] content = new Integer[size];
	/**
	 * 下一个可以存储元素的位置
	 */
	private int addIndex = 0;
	/**
	 * 下一个可以读取元素的位置
	 */
	private int readerIndex = 0;
	
	/**
	 * 增加元素
	 * @param i
	 * @throws InterruptedException
	 */
	public void add(Integer i) throws InterruptedException {
		//P 增加元素,当然需要看看是否有空位了。
		empty.acquire();
		//拿取到了空位  准备访问临界资源存储数据了
		synchronized (content) {
			//临界区资源
			content[addIndex] = i;
			addIndex = (addIndex+1)%size;
		}
		//V 已经放入一个元素  通知full有一个元素了
		full.release();
	}
	/**
	 * 消费元素
	 * @return
	 * @throws InterruptedException
	 */
	public Integer pop() throws InterruptedException {
		//P   消费元素   当然需要看看是否有元素了
		full.acquire();
		//成功分配到一个元素的消费权限  开始从临界资源拿取元素
		Integer result = null;
		synchronized (content) {
			//临界区资源
			result = content[readerIndex] ;
			readerIndex = (readerIndex+1)%size;
		}
		//V  已经取出一个元素  告知empty有一个空位了
		empty.release();
		return result;
	}
	
	
	public static void main(String[] args) {
		final Ab s = new Ab();
 		ExecutorService a = Executors.newCachedThreadPool();
 		ExecutorService b = Executors.newCachedThreadPool();
 		final Random r = new Random();
 		for (int i = 0; i < 100; i++) {
 			final int k = i;
			a.submit(()->{
				try {
					
					s.add(k);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
		}
 		for (int i = 0; i < 101; i++) {
 			
 			b.submit(()->{
 				try {
 					//Thread.sleep(r.nextInt(10000));
 					System.out.println(s.pop());
 				} catch (InterruptedException e) {
 					// TODO Auto-generated catch block
 					e.printStackTrace();
 				}
 			});
 		}
 		a.shutdown();
 		b.shutdown();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值