代码
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()
运行结果