生产者消费者模型
有什么用?
基本概念这里就不聊了,主要可简单了解一下多线程知识,熟悉了该模型之后也便于理解一些其他并发包,比如阻塞队列。像ArrayBlockQueue与下面的实现非常类似。
理解重点:
- 加锁的用处
- 条件等待队列与锁的等待队列的差别?
- ReentrantLock实现与关键字sync有什么差别?
public class ProduceComsumerTest {
//最大库存
private final static int MAX_STORE = 100;
//当前库存
private int store = 0;
final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
public void send(int num) throws InterruptedException{
if(num <= 0){
throw new IllegalArgumentException();
}
lock.lockInterruptibly();
try {
while ((store + num) > MAX_STORE){
System.out.println("仓库容量已满:" + (store + num));
notFull.await();
}
store += num;
notEmpty.signalAll();
System.out.println("生产: " + num + "个,库存数量: " + store);
}finally {
lock.unlock();
}
}
public void receivce(int num) throws InterruptedException{
if(num <= 0){
throw new IllegalArgumentException();
}
lock.lockInterruptibly();
try {
while (store < num){
System.out.println("仓库库存不足:" + (store - num));
notEmpty.await();
}
store -= num;
notFull.signalAll();
System.out.println("消费: " + num + "个,库存数量: " + store);
}finally {
lock.unlock();
}
}
//此处加锁主要为了可见性
public int getStore() {
lock.lock();
try {
return store;
}finally {
lock.unlock();
}
}
}
进阶阅读:
ArrayBlockQueue,happen-before,ReentrantLock,AQS