生产者和消费者问题中锁定的问题?

moon197896 moon197896 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

public class ManufactureConsume {
public static void main(String[] args) {
CommodityStack cs = new CommodityStack();
Manufacture m = new Manufacture(cs);
Consumer c = new Consumer(cs);
//new Thread(m).start();
new Thread(m).start();
new Thread(m).start();
new Thread(c).start();

}
}
class Commodity {
public int id = 0;
Commodity (int id) {
this.id = id;
}
public String toString() {
return "Commodity:" + id;
}
}
class CommodityStack {
static int index = 0;
static Commodity[] c = new Commodity[6];
public synchronized void push (Commodity cd) {
while (index == c.length) {
try{
this.wait();
}catch (InterruptedException e) {}
}
this.notifyAll();
c[index] = cd;
index++;
}
public synchronized Commodity pop () {
while (index == 0) {
try{
this.wait();
}catch (InterruptedException e) {}
}
this.notifyAll();
index--;
return c[index];
}
}
class Manufacture implements Runnable {
CommodityStack cs = null;
Manufacture (CommodityStack cs) {
this.cs = cs;
}
public void run() {
for (int i = 0; i < 10; i++) {
Commodity cd = new Commodity(cs.index);
cs.push(cd);
System.out.println("制造" + cd);
try {
Thread.sleep(300);
} catch (InterruptedException e ) {}
}
}
}
class Consumer implements Runnable {
CommodityStack cs = null;
Consumer (CommodityStack cs) {
this.cs = cs;
}
public void run() {
while (cs.index != 0) {
System.out.println("吃掉了" + cs.pop());
try {
Thread.sleep(200);
} catch (InterruptedException e ) {}
}
}
}


问题是,在实际运行中,会出现同生产了两个同样ID的Commodity。也会出现同时消费了两个相同ID的Commodity的问题。

也就是说,会出现一下的输出:
“
制造Commodity:3
制造Commodity:3
制造Commodity:4
吃掉了Commodity:4
制造Commodity:4
吃掉了Commodity:4
吃掉了Commodity:3
吃掉了Commodity:3
”

这种情况是不是意味着生产和消费进程未能被独占锁定。有什么方法可以解决呢?
...全文
评论 3
收藏 已收藏
分享
返回顶部
moon197896
Java SE 62,621 成员 307,251 内容