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

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){ }
}
}

}
...全文
38 回复 打赏 收藏 举报
写回复
回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
相关推荐
发帖
Java SE
加入

6.2w+

社区成员

Java 2 Standard Edition
社区管理员
  • Java SE
申请成为版主
帖子事件
创建了帖子
2005-04-01 08:01
社区公告
暂无公告