from threading import Thread
from threading import Condition
import random
li = []
cond =Condition()
def producer():
while True:
with cond:
print("生产者获取")
li.append(random.randint(0,1000))
print("生产者完成,开始通知")
cond.notify() #通知消费者, 消费将在3秒后获取锁.因为此时还没释放锁
time.sleep(3)
def consumer():
while True:
with cond:
print("\t消费者获取")
while len(li) == 0:
print("\t消费者 没法消费,等待中....")
cond.wait()
i = li.pop()
print("\t消费了 :" , i)
cond.notify()
ts = []
ts.append(Thread(target=producer))
ts.append(Thread(target=consumer))
for t in ts:
t.start()
for t in ts:
t.join()