生产者消费者设计模式
package pr.sn.lockQueueTest;
import java.util.LinkedList;
/**
* @Description: 使用notify和wait 配合线程来实现阻塞队列
* 情景1:当仓库满时 生产者阻塞 等待消费者消费 消费者消费的同时通知生产者继续生产
* 情景2:当仓库为空时 消费者阻塞 等待生产者生产 生产者一生产 立马通知消费者消费
* @Author: songbiao
*/
public class NotifyAndWait {
public static void main(String[] args) {
Storage storage = new Storage();
Producer producer = new Producer(storage);
Consumer consumer = new Consumer(storage);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
//1.首先创建一个生产者
static class Producer implements Runnable{
private Storage storage;
public Producer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//生产信息
storage.put(i);
}
}
}
//2.创建一个消费者
static class Consumer implements Runnable {
private Storage storage;
public Consumer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//开始消费
storage.poll();
}
}
}
//3.创建一个仓库 供生产者生产 供消费者消费
static class Storage {
//设置仓库最大容量
private static final Integer MAX_SIZE = 10;
//创建集合用来存储数据
LinkedList storage = new LinkedList();
//存放数据
public synchronized void put(int data){
if (storage.size() == MAX_SIZE) {
//当仓库满时进行等待阻塞
try {
System.out.println("仓库已满 等待消费者进行消费....");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产者 生产数据======》"+data);
storage.push(data);
//生产完通知消费者
notify();
}
//取出数据
public synchronized void poll(){
if (storage.size() == 0) {
//当仓库为空时消费者等待生产者生产
try {
System.out.println("消费者等待生产者生产....");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//进行消费
System.out.println("消费者 开始消费==========》"+storage.poll());
//通知生产者生产
notify();
}
}
}
执行结果