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()

你可能感兴趣的:(python,windows,linux)