import threading
import random
import time
gMoney = 1000 # 初始化金额
gConsition = threading.Condition() # 锁
gTotalTimes = 10 # 总次数
gTimes = 0 # 记录执行的次数
# 生产者
class Producter(threading.Thread):
def run(self):
global gMoney
global gTimes
global gTotalTimes
while True:
money = random.randint(100, 1000)
gConsition.acquire() # 加锁
if gTimes >= gTotalTimes:
gConsition.release() # 退出要同时将锁解除掉 不然程序会处于等待状态 解锁
break
gMoney += money
print('%s生产了%d元钱,剩余%d元钱' % (threading.current_thread(), money, gMoney))
gTimes += 1
gConsition.notify_all()
gConsition.release() # 解锁
time.sleep(0.5)
# 消费者
class Consumer(threading.Thread):
def run(self):
global gMoney
global gTimes
global gTotalTimes
while True:
money = random.randint(100, 1000)
gConsition.acquire() # 加锁
while gMoney
if gTimes >= gTotalTimes:
gConsition.release()
# 当条件不满足的情况下 直接退出 不执行下面不合理的操作
return
print('%s准备消费%d元钱,剩余%d元钱 不足' % (threading.current_thread(), money, gMoney))
gConsition.wait()
gMoney -= money
print('%s消费了%d元钱,剩余%d元钱' % (threading.current_thread(), money, gMoney))
gConsition.release()
time.sleep(0.5)
def main():
# 消费
for i in range(2):
t = Consumer(name='消费者%d' % i)
t.start()
# 生产
for i in range(1):
t = Producter(name='生成者%d' % i)
t.start()
if __name__ == '__main__':
main()