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()

 

posted @ 2019-04-12 18:23  AloneInDefeat  阅读(305)  评论(0编辑  收藏  举报