一个简单的消息队列

目录

原理

实现代码

示例


原理

消息队列是一个先进先出栈,每次都处理第一项,处理完了过后会删除这个消息,这是一个简单的消息队列图:

实现代码

首先消息队列需要一个队列,我们用Python里的列表:

python 复制代码
self.queue = []

接着我们要实现把一个消息加入队列和处理消息:

python 复制代码
def push(self, text):
    self.queue.append(text)

def pull(self):
    test = self.queue[0]
    self.queue.pop()
    return test

示例

然后我们来验证一下:

python 复制代码
import time

'''
消息队列的类
'''

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")

结果:

Error 1\] author is not find... \[Error 2\] author is not find... \[Error 3\] author is not find... \[Error 4\] author is not find... \[Error 5\] author is not find... \[Error 6\] author is not find... \[Error 7\] author is not find... \[Error 8\] author is not find... \[Error 9\] author is not find... \[Error 10\] author is not find... \[Error 11\] author is not find... \[Error 12\] author is not find... \[Error 13\] author is not find... \[Error 14\] author is not find... \[Error 15\] author is not find... \[Error 16\] author is not find... \[Error 17\] author is not find... \[Error 18\] author is not find... \[Error 19\] author is not find... \[Error 20\] author is not find... Process finished with exit code 0

列表:

完整代码

python 复制代码
import time

class MessageQueue(object):
    def __init__(self):
        self.queue = []

    def push(self, text):
        self.queue.append(text)

    def pull(self):
        test = self.queue[0]
        self.queue.pop()
        return test

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")
相关推荐
路来了8 分钟前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿18 分钟前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack41 分钟前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
.30-06Springfield1 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦1 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
WJ.Polar1 小时前
Python数据容器-list和tuple
开发语言·python
qq_229644111 小时前
LucidShape 2024.09 最新
python
花好月圆春祺夏安3 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
萧鼎4 小时前
深度探索 Py2neo:用 Python 玩转图数据库 Neo4j
数据库·python·neo4j
华子w9089258594 小时前
基于 Python Django 和 Spark 的电力能耗数据分析系统设计与实现7000字论文实现
python·spark·django