import threading
import time
list=[]
lock=threading.Lock()
huofuCond=threading.Condition(lock=lock)
lock2=threading.Lock()
chihuoCond=threading.Condition(lock=lock2)
class HuoFu(threading.Thread):
def run(self):
while True:
chihuoCond.acquire()
for i in range(1,11):
list.append(i)
print("伙夫生产第{0}个馒头".format(i))
time.sleep(1)
#等待
huofuCond.acquire()
chihuoCond.notify_all()
chihuoCond.release()
huofuCond.wait()
huofuCond.release()
mantou=None
class Chihuo(threading.Thread):
def __init__(self,name=None):
threading.Thread.__init__(self)
self.name=name
def run(self):
while True:
chihuoCond.acquire()
if len(list)==0:
huofuCond.acquire()
huofuCond.notify()
huofuCond.release()
chihuoCond.wait()
chihuoCond.release()
chihuoCond.acquire()
if len(list)>0:
mantou=list.pop()
print("{0}在吃第{1}个馒头".format(threading.current_thread().name,mantou))
time.sleep(1)
chihuoCond.release()
hf=HuoFu()
c1=Chihuo('张三')
c2=Chihuo('李四')
c3=Chihuo('王五')
hf.start()
c1.start()
c2.start()
c3.start()
python(线程)之生产者与消费者模式实例
最新推荐文章于 2020-07-04 18:07:59 发布