生产者消费者模式的三种实现方式
时间:2022-07-25
本文章向大家介绍生产者消费者模式的三种实现方式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
java中生产者消费者模式的三种实现方式
生产者消费者的实现
生产者生产数据到缓冲区中,消费者从缓冲区中取数据。
如果缓冲区已经满了,则生产者线程阻塞;
如果缓冲区为空,那么消费者线程阻塞。
wait notify方式实现
1. 生产者
package com.earthchen.ProducerConsumer.waitnotify;
import java.util.Queue;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Producer extends Thread {
private final Queue<Integer> queue;
private String name;
private Integer maxSize;
public Producer(Queue<Integer> queue, String name, Integer maxSize) {
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (this.queue) {
while (queue.size() >= maxSize) {
System.out.println("队列已满");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("此时队列大小为" + queue.size() + "生产者" + name + "向队列中添加一个元素");
queue.offer(1);
queue.notifyAll();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. 消费者
package com.earthchen.ProducerConsumer.waitnotify;
import java.util.Queue;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Consumer extends Thread {
private final Queue<Integer> queue;
private String name;
public Consumer(Queue<Integer> queue, String name) {
super(name);
this.name = name;
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println("队列为空");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
System.out.println("此时队列大小为" + queue.size() + name + "消费者消费了一个元素");
queue.notifyAll();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
3. 测试类
package com.earthchen.producerconsumer.waitnotify;
import com.earthchen.ProducerConsumer.waitnotify.Consumer;
import com.earthchen.ProducerConsumer.waitnotify.Producer;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Producer(queue, "生产者" + i, 5));
thread.start();
}
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Consumer(queue, "消费者" + i));
thread.start();
}
}
}
使用阻塞队列实现
1. 生产者
package com.earthchen.ProducerConsumer.blockingqueue;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Producer extends Thread{
private BlockingQueue<Integer> queue;
private String name;
public Producer(BlockingQueue<Integer> queue, String name) {
super(name);
this.queue = queue;
this.name = name;
}
@Override
public void run() {
while (true){
try {
queue.put(1);
System.out.println(name+"生产了一个元素");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. 消费者
package com.earthchen.ProducerConsumer.blockingqueue;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Consumer extends Thread {
private BlockingQueue<Integer> queue;
private String name;
public Consumer(BlockingQueue<Integer> queue, String name) {
super(name);
this.queue = queue;
this.name = name;
}
@Override
public void run() {
while (true) {
try {
queue.take();
System.out.println("此时队列大小为" + queue.size() + name + "消费者消费了一个元素");
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. 测试类
package com.earthchen.ProducerConsumer.blockingqueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Main {
public static void main(String[] args) {
BlockingQueue<Integer> queue= new LinkedBlockingDeque<>(5);
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Producer(queue, "生产者"+i));
thread.start();
}
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Consumer(queue, "消费者" + i));
thread.start();
}
}
}
使用condition实现
- 生产者
package com.earthchen.ProducerConsumer.lock;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Producer extends Thread{
private Queue<Integer> queue;
private String name;
private Integer maxSize;
private Lock lock;
private Condition fullCondition;
private Condition emptyCondition;
public Producer(Queue<Integer> queue,String name,Integer maxSize,Lock lock,Condition fullCondition, Condition emptyCondition){
super(name);
this.queue=queue;
this.name=name;
this.maxSize=maxSize;
this.lock=lock;
this.fullCondition=fullCondition;
this.emptyCondition=emptyCondition;
}
@Override
public void run() {
while (true){
lock.lock();
while (queue.size()>=maxSize){
System.out.println("队列已满");
try {
fullCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("此时队列大小为" + queue.size() + "生产者" + name + "向队列中添加一个元素");
queue.offer(1);
fullCondition.signalAll();
emptyCondition.signalAll();
lock.unlock();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. 消费者
package com.earthchen.ProducerConsumer.lock;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Consumer extends Thread {
private Queue<Integer> queue;
private String name;
private Lock lock;
private Condition fullCondition;
private Condition emptyCondition;
public Consumer(Queue<Integer> queue, String name, Lock lock, Condition fullCondition, Condition emptyCondition) {
super(name);
this.queue = queue;
this.name = name;
this.lock = lock;
this.fullCondition = fullCondition;
this.emptyCondition = emptyCondition;
}
@Override
public void run() {
while (true) {
lock.lock();
while (queue.isEmpty()) {
System.out.println("队列为空");
try {
emptyCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
System.out.println("此时队列大小为" + queue.size() + name + "消费者消费了一个元素");
fullCondition.signalAll();
emptyCondition.signalAll();
lock.unlock();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. 测试类
package com.earthchen.ProducerConsumer.lock;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author earthchen
* @date 2018/9/20
**/
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
Lock lock=new ReentrantLock();
Condition fullCondition=lock.newCondition();
Condition emptyCondition=lock.newCondition();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Producer(queue, "生产者" + i, 5,lock,fullCondition,emptyCondition));
thread.start();
}
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Consumer(queue, "消费者" + i, lock,fullCondition,emptyCondition));
thread.start();
}
}
}
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 逐行阅读Spring5.X源码(十二)AOP源码分析,难!面试官都不一定懂!
- 逐行阅读Spring5.X源码(十三)spring事务源码分析
- 线程池ThreadPoolExecutor 源码分析,面试官也就那么回事,他怎么敢!
- Spug - 轻量级自动化运维平台
- Callable/Future 使用及原理分析,Future .get()为啥能等待呢?
- 优雅的drop掉mysql库中1TB大表
- 《剑指offer》第19天:股票交易(校对)
- SwiftyUserDefaults-封装系统本地化的框架推荐
- “使用多target来构建大量相似App”,唐巧大神理论验证(附工程代码地址)
- 小结:Swift、OC语言中多target在代码中如何区分
- 点击按钮每次都能实现图片的旋转和切换(swift)
- 多线程之NSOperation小结
- 判断一个坐标点是否在封闭曲线内的方法(swift)
- OC循环方法推荐-块循环遍历(比for循环好用)
- oc工程中oc、swift混编代码打包成静态framework踩坑笔记