python线程condition条件锁应用实例

import time
import threading
# 吃火锅鱼丸
guo = []
suo = threading.Condition()  #条件锁
# 生产者负责生产
class Produce(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire() #先锁住
        while True:
            time.sleep(1)
            guo.append("鱼丸")
            print("%s生产了一个鱼丸,现在锅里有%s个鱼丸"%(self.name,len(guo)))
            if len(guo)>=5:
                print("锅里已经有%s个鱼丸"%len(guo))
                suo.notify() # 通知
                suo.wait()   # wait等待  释放另一个线程
                
# 消费者负责消费
class Consumer(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            time.sleep(1.5)
            guo.pop()
            print("%s吃了一个鱼丸,现在锅里有%s个鱼丸"%(self.name,len(guo)))
            if len(guo)<1:
                print("锅里已经没有鱼丸了,请添加鱼丸。")
                suo.notify() # 通知
                suo.wait()# wait 等待   释放另一个线程
pro = Produce()
pro.start()
con = Consumer()
con.start()

# 汽车订单变化
Car = ["保时捷911","丰田普拉多","哈弗H5","奔驰G500","路虎","法拉利","宝马X5","奥迪A8","膜拜单车","大巴车"]
suo = threading.Condition()  #条件锁
List = []
index = -1
class car(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            global index
            time.sleep(2)
            index+=1
            List.append(Car[index])
            print("恭喜靳志龙喜提一辆%s,请继续选择你喜爱的车"%Car[index])
            suo.notify()
            if len(List)>=10:
                print("对不起,你的银行卡余额不足")
                suo.release()
                break
            else:
                suo.wait()
class carbox(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            global index
            time.sleep(0.5)
            print("仓库里还有%s辆车"%(len(Car)-index-1))
            suo.notify()
            if len(List) >= 10:
                print("哈哈,其实我们也没有车了,小哥哥")
                suo.release()
                break
            else:
                suo.wait()
aa = car()
aa.start()
bb = carbox()
bb.start()

 

转载于:https://www.cnblogs.com/aloneindefeat/p/10697758.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值