java进程间通信问题

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



import java.util.ArrayList;
import java.util.List;

public class FirstThread {
public static void main(String[] args) throws InterruptedException {
List<Object> goods = new ArrayList<>(); //储存物品的仓库,最多储存1
Thread thread1 = new Thread(()->{ //线程1,生产产品
int num = 0;
while(true) {
synchronized (goods) {
if(goods.size()==0) goods.add("商品" + ++num);
else if(goods.size()>0)
try {
goods.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生产者生产了第"+num+"个产品");

}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "生产者");
Thread thread2 = new Thread(()->{
int num = 0;
while(true) {
synchronized (goods) {
if(goods.size()>0) goods.remove("商品"+ ++num);
else if (goods.size()==0)
goods.notify();
System.out.println("消费者消费了第"+num+"个产品");

}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "消费者");
thread1.start();
thread2.start();
}
}

按理来说每个对应的num只有一句输出,但是结果却会出现下面这样的情况

有没有好心人能解答一下,我已经知道怎么能得到我想要的结果,只是单纯想知道这是为什么,谢谢。
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
Little  BigUs
Java 51,407 成员 86,128 内容