使用列表模拟物品池,生产者往里放置东西,而消费者从池中获取物品。物品池满时生产者等待,空时消费者等待。假设物品池里面能够容纳5个元素,每个元素都是1-1000之间的整数。请编写代码实现并查看运行结果。
import threading
from random import randint
from time import sleep
class producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global x
while True:
sleep(1)
con.acquire()
if len(x)==5:
print('生产者等待....')
con.wait()
else:
r=randint(1,1000)
print('producer:',r)
x.append(r)
con.notify()
con.release()
class consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global x
while True:
sleep(3)
con.acquire()
if not x: