Producer-Consumer solution using wait(), notify(), park() and unpark()

本文探讨了Java中多线程同步的基本概念,通过生产者-消费者问题详细介绍了wait()和notify()方法以及LockSupport类中的park()和unpark()方法的使用方式,并对比了两者的差异。

1. Introduce

In java, mutil-threads are used everywhere, applications not only take advantages of mutil-threads improving efficiency, but also encounter some confusing problems especially when threads are not synchronized correctly. Fortunately, java provides some basic primitives for synchronizing.

Producer-Consumer problem is a classic synchronization problem, in that situation a consumer is usually consuming util condition is not satisfied, then a producer starts to produce to make condition satisfied again, the consumer keeps waiting while producing.

2. wait() and notify()

Let's use wait() and notify() to illustrate producer-consumer problem. wait() and notify() are methods of Object class. Once a object's wait() is called, the current thread immediately suspends and waits until either another thread invokes notify() or notifyAll() method. Note that the current thread must own this obejct's monitor. The following codes will explain it.

       Thread consumer = new Thread(){

            @Override
            public void run() {

                // own blocker's monitor
                synchronized (blocker){

                    while(true){

                        // wait for producer to produce product
                        blocker.wait();

                        // consume product until product is used out
                        while (product > 0){
                            product--;
                            System.out.println("consume one product ...");
                        }
                    }
                }
            }
        };

        Thread producer = new Thread(){

            @Override
            public void run() {

                while(true){

                    // own blocker's monitor
                    synchronized (blocker){

                        // produce product when product is used out
                        if (product < 1){
                            product++;
                            System.out.println("produce one product ...");
                        }

                        // notice consumer to consume product
                        blocker.notify();
                    }
                }
            }
        };

        consumer.start();
        producer.start();

Notice that in above codes, wait() is invoked within a loop[ while (product <= 0) ] that rechecks condition upon return, it is because that wait() may be waken up spuriously, a so-called spurious wakeup.

(For more information about spurious wakeup, see multithreading - Do spurious wakeups in Java actually happen? - Stack Overflow).

3. park() and unpark()

park() and unpark() are methods in LockSupport class, play a role similar to wait() and notify(), but a important difference is that park() and unpark() don't require any lock, an example of producer-consumer solution using park() and unpark() could be written as follows:

        Thread consumer = new Thread(){

            @Override
            public void run() {

                // block on blocker
                while(true){
                    // wait for producer to produce product
                    while (product.get() <= 0){
                        LockSupport.park();
                    }

                    // consume product until product is used out
                    while (product.get() > 0){
                        product.decrementAndGet();;
                        System.out.println("consume one product ...");
                    }
                }
            }
        };

        Thread producer = new Thread(){

            @Override
            public void run() {

                while(true){

                    // produce product when product is used out
                    if (product.get() < 1){
                        product.incrementAndGet();
                        System.out.println("produce one product ...");
                    }

                    // notice consumer to consume product
                    LockSupport.unpark(consumer);
                }
            }
        };

        consumer.start();
        producer.start();

Note: Like wait(), park() could also be waken up spuriously, should be wrapped in a loop.

4. Difference

Compared to park() and unpark(), wait() and notify() have more limitions, for example:

1. notify() are limited to be after wait(), otherwise it will occur dead-lock.

2. The current thread must own the obejct's monitor before calling notify() and wait()

3. notify() chooses one thread arbitrarily to wake up if there are many threads waitting on the same object, while unpark() specifies which thread to be awakened.

👉👉👉 自己搭建的租房网站:全网租房助手,m.kuairent.com,每天新增 500+房源

代码下载地址: https://pan.quark.cn/s/a4b39357ea24 在计算机视觉技术中,数据集扮演着训练和评估模型的核心角色。Labelme作为一个广受欢迎的开源工具,能够支持用户以交互方式对图像进行标注,而COCO(Common Objects in Context)则是一种被广泛采纳的数据集标准格式,适用于包括物体检测、图像分割在内的多种任务。本文将详细阐述如何将Labelme生成的标注数据转换为COCO数据集的标准格式。 Labelme标注的图像在输出为JSON格式时,会包含以下核心内容: 1. `version`: 指明JSON文件的版本信息。 2. `flags`: 目前未定义或保持为空,预留用于未来的功能扩展。 3. `shapes`: 列表形式存储对象的形状信息,每个形状项包含`label`(对象类别名称),`points`(构成对象边缘的多边形顶点),以及`shape_type`(通常为“polygon”)。 4. `imagePath`和`imageData`: 提供原始图像的存储路径和二进制数据,便于后续图像的还原。 5. `imageHeight`和`imageWidth`: 明确标注图像的垂直和水平尺寸。 COCO数据集的标准格式中定义了三种主要的标注类型: 1. Object instances(目标实例):主要用于执行物体检测任务。 2. Object keypoints(目标上的关键点):适用于人体姿态估计相关应用。 3. Image captions(看图说话):用于生成图像的文本描述。 COCO的JSON结构中包含以下基本组成部分: 1. `images`:记录图像的基本属性,包括`height`(高度)、`...
内容概要:本文围绕基于Basisformer模型的时间序列锂离子电池SOC(State of Charge,荷电状态)预测展开研究,利用PyTorch深度学习框架构建并训练模型,旨在提升锂电池SOC估计的准确性与鲁棒性。该方法融合Transformer架构的核心机制,通过引入基函数(Basis)分解策略,有效捕捉电池充放电过程中长时序、非线性动态特征,增强模型对复杂工况的适应能力。研究不仅详细阐述了Basisformer的网络结构设计、注意力机制优化与训练流程,还提供了完整的Python代码实现方案,涵盖数据预处理、模型搭建、损失函数定义、训练验证及结果可视化等环节,便于科研人员快速复现、调优并拓展至其他电池状态预测任务。; 适合人群:具备一定深度学习与Python编程基础,熟悉PyTorch框架,从事电池管理系统(BMS)、新能源汽车、储能系统、智能传感等领域的高校研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于动力电池与储能系统的实时SOC估算模块,提升系统安全性与能量利用效率;②作为学术研究的基础模型,用于复现、改进基于Transformer的时间序列预测方法在电化学系统中的应用;③为数据驱动的电池健康状态(SOH)、剩余使用寿命(RUL)联合估计提供可扩展的技术框架。; 阅读建议:建议读者结合所提供的代码与公开电池数据集(如NASA、CALCE等)进行动手实践,深入理解模型的输入输出结构与时序建模逻辑,同时可尝试引入温度、老化周期等多维特征,或融合物理模型构建混合预测架构,以进一步提升预测精度与泛化能力。
内容概要:本文系统阐述了基于动态规划算法优化插电式混合动力电动汽车(PHEV)能源管理的技术方案,结合Matlab与Simulink工具实现完整的仿真建模与代码开发。通过动态规划这一全局优化方法,在已知驾驶循环条件下,精确求解发动机、电机及电池之间的最优能量分配策略,以实现燃油消耗与排放的最小化目标,解决PHEV多能源路径规划中的复杂决策问题。文中提供了详尽的仿真模型构建流程与算法实现步骤,涵盖车辆动力学建模、能量管理架构设计、状态空间定义、代价函数构造、最优控制律求解及结果可视化分析等关键环节,全面揭示PHEV能量管理系统的内在机制与优化逻辑。; 适合人群:具备一定Matlab/Simulink编程基础,从事新能源汽车、智能控制、电力电子、自动化或交通运输工程等相关领域的研究生、科研人员及工程技术人员,尤其适合专注于车辆能量管理策略、节能控制算法研究的专业人士。; 使用场景及目标:①深入掌握动态规划在混合动力汽车能量管理中的理论基础与工程实现方法;②学习如何在Matlab/Simulink环境中搭建PHEV整车仿真平台并实施多目标优化仿真;③为学术研究、学位论文撰写或实际工程项目提供可复用的算法框架、模型模板与技术支持,支撑后续对等效燃油消耗最小化策略(ECMS)、模型预测控制(MPC)、实时优化算法等的对比研究与性能评估。; 阅读建议:建议读者结合所提供的完整代码与Simulink模型文件,逐模块调试运行,重点理解状态变量离散化处理、前后向递推求解过程、惩罚项设置以及边界条件处理等核心技术细节,同时可进一步拓展应用于不同工况场景、不同车型结构或与其他优化算法(如庞特里亚金极小值原理PMP)的对比验证,从而深化对PHEV能量管理实时性与全局性平衡问题的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值