public class ProducerConsumerDemo
{

public static void main(String[] args)
{
SyncStack ss = new SyncStack();
Producer p1 = new Producer(1, ss);
Producer p2 = new Producer(2, ss);
Consumer c1 = new Consumer(1, ss);
Consumer c2 = new Consumer(2, ss);

new Thread(p1).start();
new Thread(p2).start();

new Thread(c1).start();
new Thread(c2).start();
}

}class WoTou
{
private int id;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public WoTou(int id)
{
this.id = id;
}

public String toString()
{
return "馒头" + id;
}
}class SyncStack
{
Vector<WoTou> ss = new Vector<WoTou>(6);

public synchronized void push(WoTou o)
{
while (ss.size() > 6)
{
try
{
this.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}

}
this.notifyAll();
ss.add(o);
}

public synchronized WoTou pop()
{
while (ss.isEmpty())
{
try
{
this.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.notifyAll();
return ss.remove(0);
}
}class Producer implements Runnable
{
private int id;
SyncStack ss = null;

Producer(int id, SyncStack ss)
{
this.id = id;
this.ss = ss;
}

@Override
public void run()
{

for (int i = 0; i <10; i++)
{
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产者" + id + ",生产了" + wt);
try
{
Thread.sleep((int) Math.random() * 100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}class Consumer implements Runnable
{
private int id;
SyncStack ss = null;

Consumer(int id, SyncStack ss)
{
this.id = id;
this.ss = ss;
}

@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
WoTou wt=ss.pop();
System.out.println("消费者" + id + ",吃了" +wt);
try
{
Thread.sleep((int) Math.random() * 500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}输出的结果如下:为什么没有生产就消费了???
消费者2,吃了馒头0
生产者2,生产了馒头0
消费者1,吃了馒头0
生产者1,生产了馒头0
消费者2,吃了馒头1
生产者2,生产了馒头1
生产者1,生产了馒头1
生产者2,生产了馒头2
消费者2,吃了馒头2
消费者1,吃了馒头1
生产者2,生产了馒头3
消费者2,吃了馒头3
生产者2,生产了馒头4
消费者1,吃了馒头2
消费者2,吃了馒头4
生产者2,生产了馒头5
生产者1,生产了馒头2
消费者2,吃了馒头6
消费者1,吃了馒头5
生产者2,生产了馒头6
消费者2,吃了馒头3
生产者2,生产了馒头7
消费者1,吃了馒头7
生产者1,生产了馒头3
生产者2,生产了馒头8
消费者2,吃了馒头8
消费者1,吃了馒头4
消费者2,吃了馒头9
生产者2,生产了馒头9
生产者1,生产了馒头4
消费者2,吃了馒头5
生产者1,生产了馒头5
消费者1,吃了馒头6
生产者1,生产了馒头6
消费者1,吃了馒头7
生产者1,生产了馒头7
生产者1,生产了馒头8
消费者1,吃了馒头8
生产者1,生产了馒头9
消费者1,吃了馒头9

解决方案 »

  1.   

    也许是因为push方法有些问题,该方法先调用了this.notifyAll();然后才调用ss.add(o);
    这种顺序可能会在消费者被唤醒时,并没有将生产的东西放进去
      

  2.   

    不是没有生茶就消费而是
    生产完后,下一句是打印XXX生产
    而在生产完和打印之前 消费方法和消费打印语句执行了。你写的生产消费是对的。如果你想生产总是打印在消费前,可以把System.out.println()也写在synchronized(){}中。
      

  3.   

    你先让消费者的线程wait(),等生产者生产完之后再将消费者notifyAll(),然后让生产者wait(),等消费者消费完,先this.notifyAll()即唤醒生产者进程,然后将自己this.wait()