python队列与多线程——生产者消费者模型

队列相关知识点

多线程相关知识点

import random
import time
from queue import Queue
import threading


class Consumer(threading.Thread):
    def __init__(self, name, Q: Queue):
        super(Consumer, self).__init__()
        self.name = name
        self.Q = Q

    def run(self):
        while True:
            time.sleep(1)
            if Q.empty():
                print("Hans家没货了")
                continue
            n = random.randint(1, 10)
            n = Q.qsize() if n > Q.qsize() else n
            consumer_list = []
            for i in range(n):
                item = self.Q.get()
                consumer_list.append(item)
            print(f"{self.name}消费了{consumer_list}")


class Producer(threading.Thread):
    def __init__(self, name, Q: Queue, item_list: list):
        super(Producer, self).__init__()
        self.name = name
        self.Q = Q
        self.item_list = item_list

    def run(self):
        while True:
            time.sleep(1)
            m = random.randint(1, 3)
            producer_list = []
            for i in range(0, m):
                n = random.randint(0, len(self.item_list) - 1)
                self.Q.put(self.item_list[n])
                producer_list.append(self.item_list[n])
            print(f"{self.name}生产了{producer_list}")
            print(f"库存:{str(list(self.Q.queue))}")


if __name__ == '__main__':
    Q = Queue(20)
    item_list = ["apple", "huawei", "xiaomi", "meizu", "oppo", "sansumg"]
    producer = Producer("Hans", Q, item_list)
    consumer = Consumer("Lily", Q)
    producer.start()
    consumer.start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值