生产者消费者模型之lock版本
package com.company.run;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 生产者消费者模型 等待和唤醒
* lock版本
*/
//馒头
class Moutou{
private int id;
public Moutou(){}
public Moutou(int id){
this.id=id;
}
public int getId( ) {
return this.id;
}
}
//容器类
class Score {
private LinkedList<Moutou> list =new LinkedList<>();
final Lock lock = new ReentrantLock();//创建锁 ReentrantLock可重入锁
final Condition notFull = lock.newCondition();//条件变量是否满
final Condition notEmpty = lock.newCondition();//条件变量是否空
private final int max=20;//最大容量
//生产
public void push(Moutou moutou) {
try {
lock.lock();
while(list.size()==max) {
notFull.await();//已经满了等待消费者消费
System.out.println("馒头已经满了");
}
list.add(moutou);
System.out.println("生产了编号是" +list.size()+ "个馒头");
notEmpty.signal();//notEmpty唤醒消费者消费
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//消费
public Moutou pop() {
try {
lock.lock();
while (list.size()== 0) {
System.out.println("没有馒头啊!!!");
notEmpty.await();//空了等待生产者生产
}
Moutou m = list.remove();
System.out.println("消费了馒头1个还剩" + list.size()+ "个");
notFull.signal();//消费了唤醒生产者生产
return m;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
}
//生产者
class Product implements Runnable{
Score s;
@Override
public void run() {
while(true){
Moutou m=new Moutou();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.push(m);
}}
public Product(Score Score){
this.s=Score;
}
}
//消费者
class Consumer implements Runnable{
Score s;
@Override
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.pop();
}
}
public Consumer(Score s){
this.s=s;
}
}
public class ProductCousmer {
public static void main(String[] args) throws InterruptedException {
Score s=new Score();
Thread t1 = new Thread(new Product(s));
Thread t2 = new Thread(new Consumer(s));
t1.start();
t2.start();
}
}
notFull后面有一个队列
notEmpty有一个队列
唤醒不同的队列和等待不同的队列