''' Lock版的生產者和消費者模式 ''' import threading import random import time gMoney = 1000 # 原始金額 gLoad = threading.Lock() gTime = 0 # 生產次數 class Producer(threading.Thread): def run(self): global gMoney global gTime while True: gLoad.acquire() if gTime < 20: gTime += 1 money = random.randint(50,500) gMoney += money print("生產線程%s生成了%d元,剩餘%d元"%(threading.current_thread(),money,gMoney)) else: gLoad.release() break gLoad.release() time.sleep(1) class Consumer(threading.Thread): def run(self): global gMoney while True: gLoad.acquire() money = random.randint(50,500) if money > gMoney: print("%s線程結束,須要消費%d,本金爲%d"%(threading.current_thread(), money, gMoney)) gLoad.release() break else: gMoney -= money print("消費線程%s消費了%d元,剩餘%d元" % (threading.current_thread(), money, gMoney)) gLoad.release() time.sleep(1) def main(): for x in range(5): t = Producer(name="生產者線程%s"%x) t.start() for x in range(3): t = Consumer(name="消費者線程%s"%x) t.start() if __name__ == '__main__': main()