代码
from queue import Queue
import time
import threading
q = Queue(maxsize=10)
def product(name):
count = 0
while True:
if not q.full():
count += 1
q.put('{}-玩具枪-{}'.format(name, count))
print('{}: (生产了玩具枪:{}把) '.format(name, count))
time.sleep(0.5)
else:
print("队列满了,正在等待 ")
time.sleep(2)
def consume(name):
while True:
if not q.empty():
print('{}: (使用了{}) '.format(name, q.get()))
time.sleep(1)
else:
print("队列空了,正在等待 ")
time.sleep(2)
def main():
names = ['thomas', 'clos', 'luanke', 'mark']
for name in names:
if name == "thomas":
t = threading.Thread(target=product, args=(name,))
t.start()
else:
t = threading.Thread(target=consume, args=(name,))
t.start()
if __name__ == '__main__':
main()
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210414135809971.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01hcmtBZGM=,size_16,color_FFFFFF,t_70)