您的位置:首页 > 其它

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

2015-02-13 00:16 405 查看
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+" 号缓冲区已取出");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: