我有两种类型的生产者,它们生产两种不同类型的元素,以及两种不同类型的使用者,因此,type1生产者应该为type1创建元素,依此类推。
我尝试为锁添加更多条件,为每种类型创建不同的函数,但无济于事
public class SharedBuffer {
private ReentrantLock l= new ReentrantLock();
private Condition producer = l.newCondition();
private Condition consumer = l.newCondition();
private Condition consumerType2 = l.newCondition();
private Element buffer[];
private int in, out, size;
public Sharedbuffer(int size){
buffer = new Element[size];
for(int i=0; i<buffer.length;i++) {
buffer[i]= null;
}
in=out=size=0;
}
public void deposit(Element new) throws InterruptedException{
l.lock();
try {
while(size>=buffer.length)
producer.await();
buffer[in]=new;
in = (in+1)%buffer.length;
size++;
if(new.getType()==1) {
consumer.signal();
}
else {consumerType2.signal();}
} finally {
l.unlock();
}
}
public Element extract() throws InterruptedException{
l.lock();
try {
while(size<=0) {
consumer.await();}
Element new = buffer[out];
out = (out+1)%buffer.length;
size--;
producer.signal();
return new;
} finally {
l.unlock();
}
}
public Element extractType2() throws InterruptedException{
l.lock();
try {
while(size<=0) {
consumerType2.await();}
Element new = buffer[out];
out = (out+1)%buffer.length;
size--;
producer.signal();
return new;
} finally {
l.unlock();
}
}
问题在于,类型1使用者有时会消耗类型2元素,反之亦然。