java模拟生产者消费者实现线程同步通信
前提:线程知识、操作系统知识、java基础
```java
package Thread_commutation;//
import java.util.ArrayList;
import java.util.List;
// Created by Chenglong Shi on 2021/11/7.
// Only can use to study
// Once found commercial or illegal use will be pursued to the end
// Banning plagiarism
// Email:2230307855@qq.com
// 内部可能含有拼音和汉语注释
// by 史成龙
// 方法:
//
// synchronized 实现的同步可以在感知方面认为是同时的 一个生产一个消耗
// 必须定义相同的同步资源变量 如下面程序中的两个线程块里的num变量
// 两个num看似没有联系,实则在执行与等待 以及唤醒过程中已经达到同步计数的效果
public class ProducerAndConsumerProblem {
public static void main(String[] args) {
//模拟存储商品的集合
List<Object> goods=new ArrayList<Object>();
//以goods对象为锁
long start=System.currentTimeMillis();
//生产者线程,用于生产商品并放入商品集合
Thread Producer=new Thread(()->{
int num=0;
while(System.currentTimeMillis()-start<=1000){
//用synchronized 来同步商品生产和消费
synchronized (goods){
//有商品就等待消费者消费
if(goods.size()>0){
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//无商品,生产者继续生产商品
else{
goods.add("商品"+String.valueOf(++num));
System.out.println("生产产品"+num);
}
}
}
});
//下边的代码可以自己从反面来理解一下
Thread Consumer=new Thread(()->{
int num=0;
while(System.currentTimeMillis()-start<=1000){
synchronized (goods){
if(goods.size()<=0) goods.notify();
else {
goods.remove("商品"+String.valueOf(++num));
System.out.println("消费产品"+num);
}
}
}
});
//start two threads simultaneously
Producer.start();
Consumer.start();
}
}