文档介绍:import ;
/*
* 定义临界资源:缓冲队列
* */
public class Buffers {
JTextArea ta;
static final int productBufferNum = 10; //缓冲单元数
ProductBuffer pBuffer[] = new ProductBuffer[productBufferNum]; //缓冲队列
int in = 0; //缓冲单元指针,用于放产品get()
int out = 0; //缓冲单元指针,用于取产品put()
int consumeProductNo; //记录消费产品的编号
int usedBufferNum = 0; //记录缓冲队列已使用的缓冲单元个数
public Buffers(JTextArea ta){
= ta;
//初始化
for(int j=0; j<productBufferNum; j++){
pBuffer[j] = new ProductBuffer();
}
for(int i=0; i<productBufferNum; i++){
pBuffer[i].product = -1;
pBuffer[i].hasProduct = false;
}
}
//取产品
public synchronized void get(int id){
//缓冲队列空则等待
if(usedBufferNum == 0){
try{
();
}catch(Exception e){
();
}
}
consumeProductNo = pBuffer[out].product; //取出产品
pBuffer[out].product = 0; //清空缓冲单元
pBuffer[out].hasProduct = false; //置"无产品"标识
usedBufferNum--;
//输出本次取产品后缓冲队列的情况
("消费者"+id+"将产品"+consumeProductNo+"从缓冲单元"+out+"取出,缓冲队列状态如下:\n");
printBuffer();
out=(out+1)%productBufferNum; //更新指针
//唤醒等待线程
();
}
//放产品
public synchronized void put(int productNo, int id){
//缓冲队列满则等待
if(usedBufferNum == productBufferNum){
try{
();
}catch(Exception e){
();
}
}
pBuffer[in].product = productNo; //放产品
pBuffer[in].hasProduct = true;