python中多线程消费者生产者问题

threading的消费,生产实现

# 面向对象的消费者和生产者模式.
"""
多线程.
"""
from threading import Thread
import queue
import random
import time


class Producer(Thread):
    def __init__(self, queue):  # 重写.
        super().__init__()  # 加入父类init.
        self.queue = queue

    def run(self):  # call start()时 就会调用run(run为单线程).
        while True:
            item = random.randint(0, 99)  # left is closed and right is closed.
            self.queue.put(item)
            print("Producer-->%s" % item)
            time.sleep(1)


class Consumer(Thread):
    def __init__(self, queue):  # 重写.
        super().__init__()  # 加入父类init.
        self.queue = queue

    def run(self):  # call start()时 就会调用run(run为单线程).
        while True:
            item = self.queue.get()
            print("Consumer-->%s" % item)
            self.queue.task_done()


# main + tab
if __name__ == '__main__':
    q1 = queue.Queue()

    p = Producer(q1)
    c = Consumer(q1)
    p.start()
    c.start()
    p.join()
    c.join()

你可能感兴趣的:(python)