python中多執行緒消費者生產者問題

One of them發表於2018-08-23

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

相關文章