2018.5.30课堂练习线程--抢票--蒸包子代码

#多线程互相影响
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()

运行:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值