本帖最后由 何仕映 于 2013-3-24 14:06 编辑
下面这个生产消费的例子,我是想暴露出wait()和notify()的在多个线程干一件事情时线程间通信的不足。我想看到的安全问题是生产两次消费一次或者生产两次消费一次。但是在执行过程中还出现了另一个问题就是一大片的销售没有生产,按代码上来执行应该是如果销售了没有生产,标志位是不会变的,是不会再销售的,为什么还会有那么多销售打出来呢?
下面是代码:请高手帮帮忙分析一下- class Goods //定义商品类
- {
- private String name;//商品的属性
- private int num = 0;//商品的编号
- boolean flag = false;//定义标志位,如果为真代表已生产商品,等待销售
- Goods(String name) //构造函数
- {
- this.name = name;
- }
-
- public void Product() //商品的生产
- {
- synchronized(this)
- {
- if(flag)
- try{this.wait();}catch(Exception e){}//如果商品生产了则等待
- System.out.println(Thread.currentThread().getName()+"Product \t"+this.name+"\t编号是"+(++num));
- flag = true;
- this.notify();
- }
- }
- public void Sell() //商品的销售
- {
- synchronized(this)
- {
- if(!flag)
- try{this.wait();}catch(Exception e){}//如果商品卖出了,则等待
- System.out.println(Thread.currentThread().getName()+"Sell \t"+this.name+"\t编号是"+num);
- flag = false;
- this.notify();
- }
- }
- }
- class Product implements Runnable //商品生产的类
- {
- Goods g;
- Product(Goods g)
- {
- this.g = g;
- }
- public void run()
- {
- while(true)
- {
- g.Product();
- }
- }
- }
- class Sell implements Runnable //商品销售的类
- {
- Goods g;
- Sell(Goods g)
- {
- this.g = g;
- }
- public void run()
- {
- while(true)
- g.Sell();
- }
- }
- class ProductSellDemo //主函数
- {
- public static void main(String[] args)
- {
- Goods g = new Goods("IPhone");
-
- new Thread(new Product(g)).start();//生产线程
- new Thread(new Product(g)).start();
- new Thread(new Sell(g)).start();//销售线程
- new Thread(new Sell(g)).start();
- }
- }
复制代码 下面是执行过程中的问题截图
|
|