我的兩個執行緒,生產和消費,不能很好地作業。當我運行這段代碼時,控制臺會一一列印“生產”和“消費”。然后,它停止了,程式仍在運行>
class BufferMutex {
private char [] buffer;
private int count = 0, in = 0, out = 0;
private ReentrantLock mutex = new ReentrantLock();
private Condition okProduce = mutex.newCondition();
private Condition okConsume = mutex.newCondition();
BufferMutex(int size) {
buffer = new char[size];
}
public void put(char c) {
mutex.lock();
try {
while(count == buffer.length) {
okProduce.await();
}
System.out.println("Producing " c " ...");
buffer[in] = c;
in = (in 1) % buffer.length;
count ;
okProduce.signalAll();
}catch(InterruptedException ie) {
ie.printStackTrace();
}finally {
mutex.unlock();
}
}
public char get() {
mutex.lock();
char c = buffer[out];
try {
while (count == 0) {
okConsume.await();
}
out = (out 1) % buffer.length;
count--;
System.out.println("Consuming " c " ...");
okConsume.signalAll();
}catch(InterruptedException ie) {
ie.printStackTrace();
}finally {
mutex.unlock();
}
return c;
}
}
uj5u.com熱心網友回復:
您似乎讓生產者向生產者發出信號,而消費者向消費者發出信號。你不想換那些嗎?生產者不應該向消費者發出信號嗎?反之亦然?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477525.html
