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()
  • 相关阅读:
    云计算大会有感—MapReduce和UDF
    C++对象模型
    oracle中LAG()和LEAD()等分析统计函数的使用方法(统计月增长率)
    .NET MVC学习笔记(一)
    解决mysql控制台查询数据乱码的问题,有图有真相
    java linux 项目常常无故被关闭 进程无故消息
    android点滴之ContentObserver的使用
    GEF-whole-upload教程中遇到的问题及解决方案
    第四届蓝桥杯JavaB组省赛真题
    第四届蓝桥杯JavaA组省赛真题
  • 原文地址:https://www.cnblogs.com/aloneindefeat/p/10697758.html
Copyright © 2011-2022 走看看