package com.zouch.practice;
import java.util.LinkedList;
/**
* @author Zouch
* @date 2020/05/09 9:20
* @description
*/
public class ProductorAndCustomer {
private static int MAX_VALUE = 10;
private volatile int flag = 1;
LinkedList<String> linkedList = new LinkedList<>();
Object object = new Object();
/**
* 生产者
* @throws InterruptedException
*/
public void product() throws InterruptedException {
synchronized (linkedList){
while (linkedList.size()==MAX_VALUE){
System.out.println("仓库满了,生产者停止!");
linkedList.wait();
}
linkedList.push("商品"+ flag);
System.out.println("生产者生产了一个产品"+"商品"+ flag);
flag++;
linkedList.notifyAll();
}
}
/**
* 消费者
* @throws InterruptedException
*/
public void custome() throws InterruptedException {
synchronized (linkedList){
while (linkedList.size()==0){
System.out.println("仓库无货");
linkedList.wait();
}
linkedList.pop();
System.out.println("消费者消费了一个产品,剩余商品数为"+linkedList.size());
linkedList.notifyAll();
}
}
//main函数调用
public static void main(String[] args) {
ProductorAndCustomer productorAndCustomer = new ProductorAndCustomer();
new Thread(new Runnable(){
@Override
public void run() {
try {
for (int i=1; i<500;i++){
productorAndCustomer.product();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i=1; i<500;i++){
productorAndCustomer.custome();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}