import threading
from queue import Queue
import time
q = Queue()classProduct(threading.Thread):""" 生产者线程类 """defrun(self):
count =0whileTrue:if q.qsize()<50:for i inrange(200):
count+=1
goods ="第{}个商品".format(count)
q.put(goods)print("生产:",goods)
time.sleep(2)classConsumer(threading.Thread):""" 消费者线程类 """defrun(self):whileTrue:if q.qsize()>10:for i inrange(3):
a = q.get()print(" 获得商品:", a)else:
time.sleep(2)
p = Product()
p.start()for i inrange(5):
c = Consumer()
c.start()
不用重写的方式来做:
import threading
from queue import Queue
import time
q = Queue()classProAndCons:defproduct_goods(self):whileTrue:print(q)if q.qsize()<50:for i inrange(200):
goods ="第{}个元素".format(i)
q.put(goods)print("goods:",goods)
time.sleep(2)defcons_goods(self):whileTrue:print(q)print(q.qsize())if q.qsize()>=10:for i inrange(3):
g = q.get()print("商品:",g)else:
time.sleep(2)
t = threading.Thread(target=ProAndCons().product_goods)
t.start()
time.sleep(10)for i inrange(5):print("11")
c = threading.Thread(target=ProAndCons().cons_goods)
c.start()