生产者消费者模型

生产者/消费者模型 生产者消费者模式是通过一个容器来解决生产者和消费者之间强耦合的关系。生产者和消费者彼此之间不直接通讯,而是通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者进行消费,而是先存到阻塞队列中。消费者不直接找生产者要数据,而是从阻塞队列中拿数据。阻塞队列就相当于一个缓冲区,将生产者和消费者之间进行解耦。 如果有多个生产者或者多个消费者那么他们之间的关系如下:下面来简单实现一下生产者和消费者模型这里是使用阻塞队列来作为生产者和消费者的“交易场所”。因此需要先创建一个类。由于其可能存放的各种类型的数据或者 阅读详情
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

@SuppressWarnings("all")
/**
 * 描述:
 *
 * @Author (fei)
 * @Date $(DATE)
 */
class Producer1 implements Runnable{
    private HashMap<Integer,Bank6> hashMap;

    public Producer1(HashMap<Integer,Bank6> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public void run() {
        while(true) {
            producer1();
        }
    }

    public void producer1() {
        for(int i =1;i<=6;i++) {
            if(i == 6) {
                i = 1;
            }
            Bank6 bank6 = hashMap.get(i);
            synchronized (bank6) {
                try {
                    if(bank6.getIndex() == 1) {
                        System.out.println("producer wait...");
                        bank6.wait();
                        i++;
                        continue;
                    }
                    /*while (bank6.getIndex() == 1) {
                        System.out.println("producer"+ i +" wait...");
                        bank6.wait();
                    }*/
                    Random random = new Random();
                    int n = random.nextInt(10);
                    bank6.setData(n);
                    //打印数据
                    System.out.println("produce data is :" + bank6.getData());
                    //index + 1
                    bank6.setIndex(bank6.getIndex() + 1);
                    //通知消费者
                    bank6.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Consumer1 implements Runnable{
    private HashMap<Integer,Bank6> hashMap;

    public Consumer1(HashMap<Integer,Bank6> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public void run() {
        while(true) {
            consumer1();
        }
    }

    public void consumer1() {
        for(int i =1;i<=6;i++) {
            if(i == 6) {
                i = 1;
            }
            Bank6 bank6 = hashMap.get(i);
            synchronized (bank6) {
                try {
                    if(bank6.isEmpty()) {
                        System.out.println("consumer wait...");
                        bank6.wait();
                        i++;
                        continue;
                    }

                    //print data
                    System.out.println("consumer consum: " + bank6.getData());
                    //index - 1
                    bank6.setIndex(bank6.getIndex()-1);
                    //inform producer
                    bank6.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

class Bank6 {
    private int data;

    private String name;

    private int index;

    public Bank6(String name) {
        this.name = name;
    }

    public boolean isEmpty() {
        return this.index == 0;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class ProCon6Bank {
    public static void main(String[] args) {
        HashMap<Integer,Bank6> hashMap = new HashMap<>();
        for(int i=1;i<=6;i++) {
            Bank6 bank6 = new Bank6("bank"+i);
            hashMap.put(i,bank6);
            System.out.println(hashMap.get(i).getName());
        }
        Thread producer1 = new Thread(new Producer1(hashMap));
        Thread consumer1 = new Thread(new Consumer1(hashMap));

        producer1.start();
        consumer1.start();
    }
}
SAP MM新手避坑指南:工厂间调拨用301还是303?手把手教你选对移动类型 本文深入解析SAP MM模块中工厂间调拨的301与303移动类型,帮助新手避开常见陷阱。通过对比一步法(301)和两步法(303+305)的核心差异、适用场景及财务影响,提供清晰的决策框架和实战技巧,确保库存调拨的准确性和效率。 阅读详情

相关推荐

别再乱设阻尼了!Abaqus动力分析中瑞利阻尼的α和β到底怎么算?

本文深入解析Abaqus动力分析中瑞利阻尼参数α和β的科学计算方法,帮助工程师准确设置阻尼参数以提升仿真精度。详细介绍了基于模态阻尼比的经典计算方法和多模态优化法,并结合工程案例演示参数设置流程,避免常见的阻尼设置误区。

weixin_42634811的博客 732

C++实现生产者和消费者模型

C++实现生产者和消费者模型 C++实现生产者和消费者模型1、实现细节1、单生产者-单消费者模型参考 C++实现生产者和消费者模型 1、实现细节 具体的实现逻辑是构建一个queue来存储生产的数据,queue不满时可以生产,不空时可以消费。 对于这个队列,采用阻塞队列的实现思路。 先实现构造函数,初始化一个unique_lock供condition_variable使用。 如何在类里面使用unique_lock等需要初始化,并且初始化会加锁的对象。这要研究下。我的理解是构造列表初始化,然后函数体里unl

JMW1407的博客 1万+

保姆级教程:用STM8S207R6和FD6288T自制BLDC驱动板,从原理图到代码框架搭建

本文提供了一份详细的STM8S207R6和FD6288T自制BLDC驱动板教程,涵盖从原理图设计到代码框架搭建的全过程。通过硬件选型、电源电路设计、PWM定时器配置等关键步骤解析,帮助开发者快速掌握无刷直流电机驱动技术,实现高效稳定的电机控制方案。

weixin_28729205的博客 489

Linux生产者消费者模型

文章目录生产者消费者模型为何要使用生产者消费者模型生产者消费者模型优点基于BlockingQueue的生产者消费者模型C++queue模拟阻塞队列的生产消费模型POSIX信号量POSIX信号量函数基于环形队列的生产消费模型 生产者消费者模型 为何要使用生产者消费者模型 生产者消费者模型优点 基于BlockingQueue的生产者消费者模型 C++queue模拟阻塞队列的生产消费模型 POSIX信号量 POSIX信号量函数 基于环形队列的生产消费模型 ...

2021dragon的博客 1万+

K-means在关键词聚类中的尝试

K-means在文本聚类中的尝试 K-means算法是无监督的聚类算法。它的算法思想是:先随机选取K个对象作为初始的聚类中心。然后计算每个对象与各个种子聚类中心之间的距离,把每个对象分配给距离它最近的聚类中心。聚类中心以及分配给它们的对象就代表一个聚类。一旦全部对象都被分配了,每个聚类的聚类中心会根据聚类中现有的对象被重新计算。 K-means算法的关键点在于: 初始k个聚类中心的选择 距离的计...

BigPig_LittleTail的博客 5573

百度无人车ApolloAuto使用入门

1.安装原版ubuntu 14.04 http://www.ubuntu.org.cn/download/alternative-downloads 2.安装对应ubuntu 14.04的indigo版ROS http://wiki.ros.org/indigo/Installation/Ubuntu 3.安装Apollo Kernel https://github.co

ss910的博客 3万+

linux:生产者消费者模型

本文是对于生产者消费者模型的知识总结以上就是我对于线程同步的总结。

li209779的博客 2765

十五天学会Autodesk Inventor,看完这一系列就够了(七),工程图纸

不管哪种绘图软件,二维或三维绘图,最终均需要转换成工程图纸,才能交给现场人员进行制作,这是任一产品图都要经历的过程。那本章开始,我们一起看一下Inventor是如何实现工程图纸?

Crazydoubao的博客 4915

【Linux】生产者消费者模型

🍁 🍃 🍂 🌿。

m0_60338933的博客 1903

FPGA学习笔记(一)入门背景、软件及时钟约束的概念及程序下载与固化

使用正点原子的PFPGA开拓者V2学习,通过b站上正点原子的手把手教你学FPGA-基于开拓者V2学习。

贾saisai的博客 3280

微信小程序|基于小程序+云开发制作一个租房小程序

经济发展的同时伴随着大批人群的流动,租房需求一直是持久不衰的话题,如何租好房,好租房,跟随此文一起制作一个租房小程序,让租房不再困难。

商务合作 / 项目定制 / 学习交流。个人vx:lovely_wml 4931

生产者消费者模型详解

生产者消费者模型 文章目录生产者消费者模型什么是生产者消费者模型基于BlockingQueue的生产者消费者模型单生产者单消费者模型多生产者多消费者模型 什么是生产者消费者模型 生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。这个阻塞队列就是用来给生产者和消费者

小赵小赵福星高照的博客 9639

亲测解决This application failed to start because no Qt platform plugin could be initialized.

这个问题是由于环境变量改变或者Qt的路径改变导致,解决办法是在环境变量里面重新添加Qt路径。

狂小虎/Anthony Dave的博客 KuangXiaoHu's Blogs 2927

【Linux】生产者 消费者模型

针对上述情况,将if判断改为while循环,每一次被唤醒都要被检测,只有当队列真的是不满的情况,才会进行push。发生休眠实际上就是线程切换,当线程从休眠状态被唤醒时,因为是从临界区被切走的,所以继续从临界区内部执行。供货商可以集中生产的一大批的商品 放到超市中,让消费者随时随地来买,供货商就不生产了。如:若超市火腿肠满了,就应该让消费者先消费,若超市没有火腿肠了,就应该让生产者先生产。若队列中没有数据存在,则不该让消费者消费,若队列中数据满了,不该让生产者进行生产。

qq_62939852的博客 1038

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

【Linux —— 生产者消费者模型】

生产者消费者模型是一种并发编程模型,用于解决多线程或多进程间的数据共享和同步问题。生产者和消费者,它们通过共享的缓冲区进行通信。生产者负责生成数据并将其放入缓冲区,而消费者则从缓冲区中获取数据并进行处理。生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而共享的缓冲区进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给缓冲区,消费者不找生产者要数据,而是直接从缓冲区取,平衡了生产者和消费者的处理能力。这个缓冲区就是用来给生产者和消费者解耦的。

jokr_的博客 1279

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Python生产者消费者模型

生产者消费者模型是一种解耦模型,生产者和消费者在不同的时间段内共用同一个存储空间。当生产者生产数据时,消费者可以同时从缓冲区中取出数据进行消费。这样,生产者和消费者之间相互解耦,不需要关心对方的存在,实现了高效的资源利用和并发处理。

一只程序猿子的博客 1880

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java的生产者消费者模型

前言 学完了线程后,我又去找了一些线程相关的练习题来练手,其中印象最深的就是生产者消费者模型这一块,为什么呢,因为它每一篇练习题里都有,开始没看懂,后面就去仔细研究了一下,哦,原来是这样,好像是懂了,那就来写写博客吧。哈哈哈…… 什么是生产者消费者模型 生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲

Andy-ZhangSir的博客 1695

生产者-消费者模型

什么是生产者消费者模型 生产者 - 消费者模型( Producer-consumer problem) 是一个非常经典的多线程并发协作的模型,在分布式系统里非常常见。 这个模型由两类线程和一个缓冲区组成来组成 生产者线程:生产数据,并把数据放在这个队列里面 缓冲区:存放生产者的数据的地方 消费者线程:从队列里面取数据,消费数据 运行流程 生产者和消费者在同一时间段内共用同一个存储空间 生产者往存储空间中添加产品 消费者从存储空间中取走产品 当存储空间为空时,消费者阻塞,当存储空间满时,生产者阻塞。

张三李四王五老六 9044
上一篇: (三)Redi缓存配置,持久化,订阅发布,主从复制和缓存相关问题以及解决
下一篇: Stream流和函数式编程
Java-fly
博客等级 码龄9年 13粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值