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

stone1982 stone1982 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
//我的问题是为什么缓冲区满了后生产者会继续执行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){ }
}
}

}
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
stone1982
Java SE 62,621 成员 307,251 内容