互斥问题请指教(源代码如下:)

stone1982 2005-04-01 08:01:50
//我的问题是为什么缓冲区满了后生产者会继续执行push()操作
package stone.pandc;
public class PandC{
public static void main(String arg[]){
BufStack buffer = new BufStack();
Runnable source = new Producer(buffer);
Runnable destination = new Consumer(buffer);
Thread p1 = new Thread(source);
// Thread p2 = new Thread(source);
Thread c1 = new Thread(destination);
// Thread c2 = new Thread(destination);
p1.start();
// p2.start();
c1.start();
// c2.start();
}
}
// the buffer
class BufStack {
private int index = 0;
private char buffer[] = new char[6];
private int pCounter = 1;
private int cCounter = 1;
//
public synchronized void push(char c){
while(index == buffer.length){
try{
System.out.println("the buffer is full ! waiting for the consumer !"+(pCounter++));
this.wait();
}
catch(InterruptedException e){ }
}
this.notify();
buffer[index] = c;
index++;
//System.out.println("thread "+"produced: "+c+" ");
}
//
public synchronized char pop( ){
while(index == 0){
try{
System.out.println("the buffer is empty ! waiting for the producer !"+(cCounter++));
this.wait();
}
catch(InterruptedException e){ }
}
this.notify();
index--;
return buffer[index];
}

}
// the producer thread
class Producer implements Runnable{
BufStack mybuf;

public Producer(BufStack pbuf){
mybuf = pbuf;
}

public void run( ){
char c;
for(int i = 0;i < 20;i ++){
c=(char)(Math.random()*26+ 'A');
mybuf.push(c);
System.out.println("thread "+"produced: "+c+" "+i);
try{
Thread.sleep((int)(Math.random( )*1000));
}
catch (InterruptedException e){ }
}
}

}
//the consumer thread
class Consumer implements Runnable{
BufStack mybuf;

public Consumer(BufStack pbuf){
mybuf = pbuf;
}


public void run( ){
char c;
for(int i = 0;i < 20;i ++){
c = mybuf.pop();
System.out.println("Consumed: "+c);
try{
Thread.sleep((int)(Math.random( )*1500));
}
catch (InterruptedException e){ }
}
}

}
...全文
54 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧