我正在处理消费者和生产者中的 BoundedBuffer 类,我们想在该类中使用 Semaphore,但每次使用acquire()时都会出错,错误 是:
未报告的异常 java.lang.InterruptedException; 必须被抓住或宣布被扔掉
这是代码:
import java.util.concurrent.Semaphore;
public class BoundedBuffer implements Buffer {
private static final int BUFFER_SIZE = 4;
/**
* volatile does not appear in the printed text. A discussion of
* volatile is in chapter 7.
*/
private volatile int count;
private Object[] buffer;
private int in; // points to the next free position in the buffer
private int out; // points to the next full position in the buffer
private Semaphore mutex;
private Semaphore empty;
private Semaphore full;
public BoundedBuffer() { //constractur
// buffer is initially empty
//count = 0;
in = 0;
out = 0;
buffer = new Object[BUFFER_SIZE];
mutex = new Semaphore(1);
empty = new Semaphore(BUFFER_SIZE);
full = new Semaphore(0);
}
// producer calls this method
public void insert(Object item) {
//while (count == BUFFER_SIZE)
// ; // do nothing the brach full
// add an item to the buffer
// ++count;
empty.acquire();
mutex.acquire();
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;//that to do cyrcle or to go to the begining againe
/*
if (count == BUFFER_SIZE)
System.out.println("Baker put " + item + " Shelf FULL");
else
System.out.println("Baker put " + item + " Shelf Size = " + count);
*/
mutex.release();
full.release();
}
// consumer calls this method
public Object remove() {
//Object item;
full.acquire();
mutex.acquire();
//while (count == 0)
; // do nothing the buffer is empty
// remove an item from the buffer
//--count;
Object item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
mutex.release();
empty.release();
return item;
}
}