zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    移动 WEB 开发布局方式 ---- flex 布局
    使用 flex布局 制作携程网首页
    移动 WEB 开发布局方式 ---- rem 适配布局
    使用 flexible.js + rem 制作苏宁移动端首页
    移动 WEB 布局方式之 rem 适配布局 ---- 苏宁首页案例制作
    移动 WEB 开发的布局方式 ---- 响应式布局
    简述 JavaScript 的执行机制
    vuex 的使用详解
    .Net Core — 依赖注入
    .NET Core +Angular 项目 部署到CentOS
  • 原文地址:https://www.cnblogs.com/aloneindefeat/p/10697758.html
Copyright © 2011-2022 走看看