互斥问题请指教(源代码如下:)
//我的问题是为什么缓冲区满了后生产者会继续执行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){ }
}
}
}