java进程间通信问题

Little BigUs 2021-04-29 09:14:40
下面是代码:



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只有一句输出,但是结果却会出现下面这样的情况

有没有好心人能解答一下,我已经知道怎么能得到我想要的结果,只是单纯想知道这是为什么,谢谢。
...全文
440 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ouzhijian 2021-05-08
  • 打赏
  • 举报
回复
应该是打印的时机不对 if(goods.size()==0) { goods.add("商品" + ++num); System.out.println("生产者生产了第"+num+"个产品"); } if(goods.size()>0) { goods.remove("商品"+ ++num); System.out.println("消费者消费了第"+num+"个产品"); }

51,402

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧