记录型信号量解决消费者-生产者问题
2015-02-13 00:16
441 查看
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+" 号缓冲区已取出"); } } }
相关文章推荐
- 【坑】记录型信号量/AND信号量/管程解决生产者-消费者问题
- 通过信号量机制解决生产者-消费者问题的模拟程序
- Linux多线程实践(5) --Posix信号量与互斥量(解决生产者消费者问题)
- 分别在windows和linux下用信号量解决生产者消费者问题
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
- 信号量解决生产者,消费者问题
- 用信号量解决生产者消费者问题
- 信号量解决生产者-消费者问题
- System V共享内存与信号量综合应用之生产者与消费者问题解决
- 信号量解决生产者-消费者问题
- Linux多线程实践(五 )Posix信号量和互斥锁解决生产者消费者问题
- 用条件变量和信号量解决生产者和消费者问题
- 用信号量做进程同步解决生产者和消费者遇到的奇怪问题
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
- 用信号量解决生产者消费者问题
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
- java信号量PV操作 解决生产者-消费者问题
- 1,使用信号量解决生产者-消费者问题
- Operating System-进程/线程内部通信-信号量、PV操作的实现和应用(解决哲学家进餐和生产者消费者问题)
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题