queue队列吃包子

import time
import threading
import queue
import random
#三个做包子的,一个吃包子的,采用队列形式
#创建三个生产线程和一个消费线程
class Production(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        #向队列中添加随机数当包子
        while True:
            r = random.randint(1, 100)
            qq.put(r)
            print("现在生产的是%s号包子"%r)
            time.sleep(1)

class Consumption(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            q=qq.get()
            print("已经吃掉了%s号包子"%q)
#创建队列添加生产的包子,和取出包子
qq = queue.Queue()
for i in range(3):
    Production().start()  #三个生产包子线程

Consumption().start()

'''  也可以写成这样的形式
if __name__=="__main__":
    q=queue.Queue(10)
    threads=[Production(),Production(),Production(),Proces()]
    for t in threads:
        t.start()
'''
原文地址:https://www.cnblogs.com/TKOPython/p/12444896.html