实现一边做酱香饼一边吃酱香饼
import time
import threading
import queue
class Proceducer():
def __init__(self, key, full):
self.full = full # 最多生产full个酱香饼
self.key = key # 酱香饼的号数
class Consumer():
def __init__(self, name):
self.name = name # 顾客的号数
def producer(name):
while True:
if item.qsize() < name.full: # 可以生产酱香饼
time.sleep(2)
name.key += 1
item.put(name.key)
print('酱香饼%d号生产出来了!现在有%d个酱香饼!' % (name.key, item.qsize()))
def consumer(name):
while True:
if not item.empty(): # 可以购买酱香饼
time.sleep(7) #购买时间可以自己调整
key = item.get()
print('酱香饼%d号被%s购买了!现在有%d个酱香饼!' % (key, name.name, item.qsize()))
threadLock = threading.Lock()
item = queue.Queue()
p = Proceducer(0, 10)
c1 = Consumer('一号顾客')
c2 = Consumer('二号顾客')
c3 = Consumer('三号顾客')
threading1 = threading.Thread(target=producer, args=(p,))
threading2 = threading.Thread(target=consumer, args=(c1,))
threading3 = threading.Thread(target=consumer, args=(c2,))
threading4 = threading.Thread(target=consumer, args=(c3,))
threading1.start()
threading2.start()
threading3.start()
threading4.start()
结果:
当每七秒就有顾客购买时:
当每两秒就有顾客购买时:
转载:https://blog.csdn.net/qq_44315987/article/details/102489621
查看评论