#多线程互相影响
import threading,time
#Condition:更精确的控制锁,提供了四个方法,上锁(acquire()),
# 等待(wait()),解锁(release()),唤醒(notify(),notify_all())
zhengLong=[] #蒸笼 存包子资源
class Cook(threading.Thread):
def run(self):
global zhengLong
while True: #蒸包子这个事不能停下来 可以-->wait
chi_Cond.acquire()
if len(zhengLong)==0:
print('厨师开始蒸包子..')
#1如何蒸包子 唤醒其他休眠的线程
for i in range(1,9):
print('厨师正在蒸第{0}个包子'.format(i))
zhengLong.append(i)
time.sleep(0.2)
print('厨师蒸完包子.开始呼唤吃货们 醒来吃包子厨师休眠.')
chi_Cond.notifyAll() #呼唤吃货们 醒来
chi_Cond.release()
zheng_Cond.acquire()
zheng_Cond.wait() #厨师休眠
zheng_Cond.release()
class ChiHuo(threading.Thread):
def __init__(self,C_name):
threading.Thread.__init__(self)
self.name=C_name
def run(self):
#如何吃包子 发现包子没有了 呼唤厨师 蒸包子
while True:
chi_Cond.acquire()
global zhengLong
if len(zhengLong)==0:#呼唤厨师
zheng_Cond.acquire()
zheng_Cond.notify()
zheng_Cond.release()
chi_Cond.wait() #吃货进入等待状态
else:
baozi=zhengLong.pop()
if baozi is not None:
print(self.name,'吃了第{0}个包子 剩下{1}个'.format(baozi,len(zhengLong)))
time.sleep(0.5)
chi_Cond.release()#
cook=Cook()
#创建2把锁 1: 锁厨师蒸包子的这个蒸笼
# 2:锁吃货的吃的包子和唤醒厨师这个事
chi=threading.Lock()
chi_Cond=threading.Condition(lock=chi)
zheng=threading.Lock()
zheng_Cond=threading.Condition(lock=zheng)
yuhao=ChiHuo('余浩')
mingming=ChiHuo('明明')
wenqiang=ChiHuo('文强')
denghao=ChiHuo('邓浩')
cook.start()
yuhao.start()
mingming.start()
wenqiang.start()
denghao.start()
import threading,time
#Condition:更精确的控制锁,提供了四个方法,上锁(acquire()),
# 等待(wait()),解锁(release()),唤醒(notify(),notify_all())
zhengLong=[] #蒸笼 存包子资源
class Cook(threading.Thread):
def run(self):
global zhengLong
while True: #蒸包子这个事不能停下来 可以-->wait
chi_Cond.acquire()
if len(zhengLong)==0:
print('厨师开始蒸包子..')
#1如何蒸包子 唤醒其他休眠的线程
for i in range(1,9):
print('厨师正在蒸第{0}个包子'.format(i))
zhengLong.append(i)
time.sleep(0.2)
print('厨师蒸完包子.开始呼唤吃货们 醒来吃包子厨师休眠.')
chi_Cond.notifyAll() #呼唤吃货们 醒来
chi_Cond.release()
zheng_Cond.acquire()
zheng_Cond.wait() #厨师休眠
zheng_Cond.release()
class ChiHuo(threading.Thread):
def __init__(self,C_name):
threading.Thread.__init__(self)
self.name=C_name
def run(self):
#如何吃包子 发现包子没有了 呼唤厨师 蒸包子
while True:
chi_Cond.acquire()
global zhengLong
if len(zhengLong)==0:#呼唤厨师
zheng_Cond.acquire()
zheng_Cond.notify()
zheng_Cond.release()
chi_Cond.wait() #吃货进入等待状态
else:
baozi=zhengLong.pop()
if baozi is not None:
print(self.name,'吃了第{0}个包子 剩下{1}个'.format(baozi,len(zhengLong)))
time.sleep(0.5)
chi_Cond.release()#
cook=Cook()
#创建2把锁 1: 锁厨师蒸包子的这个蒸笼
# 2:锁吃货的吃的包子和唤醒厨师这个事
chi=threading.Lock()
chi_Cond=threading.Condition(lock=chi)
zheng=threading.Lock()
zheng_Cond=threading.Condition(lock=zheng)
yuhao=ChiHuo('余浩')
mingming=ChiHuo('明明')
wenqiang=ChiHuo('文强')
denghao=ChiHuo('邓浩')
cook.start()
yuhao.start()
mingming.start()
wenqiang.start()
denghao.start()
input()
运行: