当前位置:网站首页>并发编程之生产者消费者模式
并发编程之生产者消费者模式
2022-07-26 22:42:00 【咖啡不加冰和糖】
生产者消费者是解决什么问题的?
- 多个线程之间的同步问题。
- 解决生产者和消费者的强耦合问题。
参考代码:
package Top;
import java.util.LinkedList;
import java.util.Random;
/** * @Author 86180 * @Date 2020/9/7 21:50 * @Version 1.0 **/
public class ProductorConsumer {
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue(2);
for(int i = 0; i < 3; i++){
new Thread(new Productor(messageQueue, new Message(i, "消息i")), "生产者线程"+i).start();
}
for(int i = 0; i < 1; i++){
new Thread(new Consumer(messageQueue), "消费者线程"+i).start();
}
}
}
class MessageQueue{
private int capacity;
LinkedList<Message> list;
MessageQueue(int capacity){
list = new LinkedList<>();
this.capacity = capacity;
}
public synchronized void put(Message message){
while (list.size() == capacity) {
try {
System.out.println("队列已经满,生产者等待。");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果用if来判断,要注意顺序:放在addLast前面
if(list.isEmpty())this.notifyAll();
list.addLast(message);
System.out.println(Thread.currentThread().getName()+"生产了" + message.getId());
}
public synchronized Message get(){
while(list.isEmpty()){
try {
System.out.println("队列空,生产者线程等待。");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(list.size() == capacity)this.notifyAll();//如果用if来判断,要注意顺序:放在removeFirst前面
Message message = list.removeFirst();
System.out.println(Thread.currentThread().getName()+"消费了"+ message.getId());
return message;
}
}
class Productor implements Runnable{
MessageQueue ms;
Message message;
Productor(MessageQueue messageQueue, Message message){
this.ms = messageQueue;
this.message = message;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
ms.put(message);
}
}
}
class Consumer implements Runnable{
MessageQueue ms;
Consumer(MessageQueue messageQueue){
this.ms = messageQueue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
ms.get();
}
}
}
class Message{
private int id;
private Object value;
Message(int id, Object value){
this.id = id;
this.value = value;
}
public int getId(){
return id;
}
}
定义一个Message类,表示消息队列里面存放的消息。
定义一个MessageQueue类,含put()和get()。
定义一个生产者类Productor。
定义一个消费者类Consumer。
边栏推荐
- How to open ads for profit after uni app develops apps and plug-ins: uni ad
- Select query topic exercise
- Spark source code learning - Data Serialization
- MySQL split table DDL operation (stored procedure)
- 基于Flink实时项目:用户行为分析(一:实时热门商品统计)
- Rabbit learning notes
- The basic concept of how Tencent cloud mlvb technology can highlight the siege in mobile live broadcasting services
- Flink的容错机制(checkpoint)
- 吴恩达深度学习系列教学视频学习笔记(一)——用于二分类的logistic回归函数
- 哪个证券公司开户股票佣金低,哪个股票开户安全
猜你喜欢

More than live streaming: what other eye-catching functions does Tencent cloud live mlvb plug-in have besides streaming / streaming

MySQL index optimization: scenarios where the index fails and is not suitable for indexing

Status management in Flink

Choose RTMP or RTC protocol for mobile live broadcast

Spark on yarn's job submission process

李宏毅机器学习(2017版)_P5:误差

Solve the problem that there is no ado.net entity data model in vs

Flink based real-time computing Demo - Data Analysis on user behavior

基于Flink实时项目:用户行为分析(一:实时热门商品统计)

Uni app applet app's advertising realization path: banner information flow advertising
随机推荐
Spark源码学习——Data Serialization
Calls to onsaveinstancestate and onrestoreinstancestate methods
Android——数据持久化技术(三) 数据库存储
C # conversion of basic data types for entry
李宏毅机器学习(2017版)_P3-4:回归
视频类小程序变现的最短路径:从带货到品牌营销
Flink中的状态管理
SparkSql之DataFrame
小程序直播、连线直播、直播打赏:腾讯云移动直播组件MLVB多场景直播拓展
使用tika 判断文件类型
Game project export AAB package upload Google tips more than 150m solution
Flinksql multi table (three table) join/interval join
Flink1.11 multi parallelism watermark test
VSCode2015下编译darknet生成darknet.ext时error MSB3721:XXX已退出,返回代码为 1。
Understanding of Flink checkpoint source code
Logback custom messageconverter
李宏毅机器学习(2021版)_P5-6:小梯度处理
Canal 介绍
Write the changed data in MySQL to Kafka through flinkcdc (datastream mode)
MYSQL 使用及实现排名函数RANK、DENSE_RANK和ROW_NUMBER