1.介绍
在之前我们的生产消费模式 都是基于多线程去开发的,生产者消费者模式是程序设计中非常常见的一种设计模式,被广泛运用在解耦、消息队列等场景。
但是最麻烦的就是需要平衡生产消费者,所以需要一个中介来进行调度,于是便诞生了生产者消费者模式。
使用生产者消费者模式通常需要在两者之间增加一个阻塞队列作为媒介,有了媒介之后就相当于有了一个缓冲,平衡了两者的能力。
所以我们要在合适的时机去阻塞或者唤醒我们的生产消费者,也就是阻塞的线程,那什么时候唤醒呢?
- 第一种情况是当消费者看到阻塞队列为空时,开始进入等待,这时生产者一旦往队列中放入数据,就会通知所有的消费者,唤醒阻塞的消费者线程。
- 另一种情况是如果生产者发现队列已经满了,也会被阻塞,而一旦消费者获取数据之后就相当于队列空了一个位置,这时消费者就会通知所有正在阻塞的生产者进行生产。
2.实现使用多线程 Condition 实现生产者消费者模式
import java.util.LinkedList;
/**
* @author cf
* @projectName cssa-toolbox
* @description: 阻塞队列类
* @date 2023/1/28下午 2:15
*/
public class MyBlockingQueue {
private int maxSize;
private LinkedList<Object> storage;
public MyBlockingQueue(int size) {
this.maxSize = size;
storage = new LinkedList<>();
}
/**
* put 方法被 synchronized 保护,while 检查队列是否为满,如果不满就往里放入数据并通过 notifyAll() 唤醒其他线程
* @throws InterruptedException
*/
public synchronized void put() throws InterruptedException {
while (storage.size() == maxSize) {
wait();
}
System.out.println("开始生产啦~");
storage.add(new Object());
notifyAll();
}
/**
* take 方法也被 synchronized 修饰,while 检查队列是否为空,如果不为空就获取数据并唤醒其他线程
* @throws InterruptedException
*/
public synchronized void take() throws InterruptedException {
while (storage.size() == 0) {
wait();
}
System.out.println("开始消费啦~"+storage.remove());
notifyAll();
}
}
/**
* @author cf
* @projectName cssa-toolbox
* @description: 实现生产者消费者模式
* @date 2023/1/28下午 2:16
*/
public class WaitStyle {
public static void main(String[] args) {
MyBlockingQueue myBlockingQueue = new MyBlockingQueue(10);
Producer producer = new Producer(myBlockingQueue);
Consumer consumer = new Consumer(myBlockingQueue);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class Producer implements Runnable {
private MyBlockingQueue storage;
public Producer(MyBlockingQueue storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
storage.put();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private MyBlockingQueue storage;
public Consumer(MyBlockingQueue storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
storage.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
其实实现方式不光这一种也有很多其他方式,比如:BlockingQueue、Condition 搭配ReentrantLock 也可搞定,记住上面说的点就好了。