蒸馒头的线程

蒸馒头
import threading,time
zhenglong=[] 共享数据  蒸笼
创建俩把锁 一把蒸馒头的锁 由伙夫掌管  一把吃馒头的锁  由吃货掌管
zheng_lock=threading.Lock()
zheng_Cond=threading.Condition(lock=zheng_lock)
chi_lock=threading.Lock()
chi_Cond=threading.Condition(lock=chi_lock)


class huofu(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.setName(name)
    def run(self):
        while True:
            chi_Cond.acquire()    被谁唤醒
            if len(zhenglong)==0:
        开始蒸馒头
                for i in range(1,11):
                    zhenglong.append(i)
                    time.sleep(0.5)
                    print(' 正在蒸第{0}个馒头'.format(i))
                print('馒头蒸完  唤醒吃货门开始吃馒头...')
                chi_Cond.notify_all()  唤醒了吃货们
            chi_Cond.release()唤醒了伙夫 他就释放
        伙夫 进入休眠
            zheng_Cond.acquire()
            zheng_Cond.wait()
            zheng_Cond.release()

class chihuo(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.setName(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:
                mantou=zhenglong.pop()
                print('{0}吃了第{1}个馒头  剩余{2}个馒头'.format(self.getName(),mantou,len(zhenglong)))
                time.sleep(0.5)
            chi_Cond.release()  解锁

W=huofu('伙夫')
xiaogang=chihuo('小刚')
xiaoming=chihuo("小明")
xiaomi=chihuo('小米')
W.start()
xiaogang.start()
xiaoming.start()
xiaomi.start()
主线程不死
input()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值