日期:2014-05-20  浏览次数:20830 次

用java写的生产者消费者程序为什么输出的时候只显示生产者生产了多少,但是始终不能显示消费者消费了多少
package com.a.b;

public class ProducerConsumer {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
syncStack ss=new syncStack();
Producer p=new Producer(ss);
Consumer c=new Consumer(ss);
new Thread(p).start();
new Thread(c).start();

}

}
class WoTou{
int id;
WoTou(int id){
this.id=id;
}
public String toString(){
return "wotou:"+id;
}
}
class syncStack{
int index;
WoTou[] ss=new WoTou[6];
public synchronized void push(WoTou wt){
if(index==ss.length){
try{
this.wait();
this.notify();
}catch(InterruptedException e){
e.printStackTrace();
}

ss[index++]=wt;
}
 }
public synchronized WoTou pop(){
if(index==0){
try{
this.wait();
this.notify();
}catch(InterruptedException e){
e.printStackTrace();
}
}

index--;
return ss[index];
}
}
class Producer implements Runnable{
syncStack ss=null;
Producer(syncStack ss){
this.ss=ss;
}
public void run(){
for(int i=0;i<20;i++){
WoTou wt=new WoTou(i);
ss.push(wt);
System.out.println("生产了:"+wt);
try{
Thread.sleep((int)Math.random()*1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
syncStack ss=null;
Consumer(syncStack ss){
this.ss=ss;
}
public void run(){
for(int i=0;i<20;i++){
WoTou wt=ss.pop();
System.out.println("消费了:"+wt);
try{
Thread.sleep((int)Math.random()*1000);
}catch(InterruptedException e){
e.printStackTrace();
}

}
}
}
我明明写了 System.out.println("消费了:"+wt); 这句话怎么没有发挥作用么

------解决方案--------------------
1、 public synchronized void push(WoTou wt) {
if (index == ss.length) {

index初始化为0 ss.length为6
所以这个条件就一直进不去 index也不会加加

2、这种情况下你生产后,WoTou[]里是空的,当你执行
WoTou wt = ss.pop();时
if (index == 0) { //条件成立
try {
this.wait(); //线程等待,所以它下面的消费语句就出不来了

3、this.wait();之后应该由其他线程再唤醒