package com.GoCo.data.ProdecerConsumer;
import java.util.LinkedList;
/**
* 生产者消费者简单模型
*/
public class Concurrentcomm {
///常量 可为库存
private static int MAX_VALUE = 10;
LinkedList<String> linkedList = new LinkedList<>();
Object object=new Object();
/**
* 生产者方法
*/
public void product() throws InterruptedException {
synchronized (linkedList){
while (MAX_VALUE==linkedList.size()){
System.out.println("仓库已满,【生产者】: 暂时不能执行生产任务!");
linkedList.wait();
}
linkedList.push("李四");
System.out.println("生产者:生产力一个产品 现在仓库存量有:"+linkedList.size());
linkedList.notifyAll();
}
}
/**
* 消费者方法
*/
public void customer() throws InterruptedException {
synchronized (linkedList){
while (linkedList.size()==0){
System.out.println("仓库无货,消费者:暂时不能执行消费任务");
linkedList.wait();
}
linkedList.pop();
System.out.println("【消费者】:消费了一个产品【现仓储量为】:" + linkedList.size());
linkedList.notifyAll();
}
}
public static void main(String[] args) {
Concurrentcomm con = new Concurrentcomm();
//生产
new Thread(new Runnable() {
@Override
public void run() {
try {
// for (int i = 0; i < 100; i++) {
while (true) {
con.product();
Thread.sleep(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//消费
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
// for (int i = 0; i < 100; i++) {
while (true) {
con.customer();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
java手写生产者消费者
最新推荐文章于 2024-07-10 09:44:18 发布