1 import threading 2 import time 3 import random 4 5 6 gMoney = 1000 7 gLock = threading.Lock() 8 9 class Producer(threading.Thread): 10 def run(self): 11 global gMoney 12 while 1: 13 money = random.randint(100,1000) 14 gLock.acquire() 15 gMoney += money 16 print('%s生产了%d,账户总余额%d'%(threading.current_thread(),money,gMoney)) 17 gLock.release() 18 time.sleep(0.5) 19 20 21 class Consumer(threading.Thread): 22 def run(self): 23 global gMoney 24 while 1: 25 money = random.randint(100,1000) 26 if gMoney >= money: 27 gLock.acquire() 28 gMoney -= money 29 print('%s消费了%d,账户余额%d'%(threading.current_thread(),money,gMoney)) 30 gLock.release() 31 time.sleep(0.5) 32 33 def main(): 34 for x in range(5): 35 t = Producer() 36 t.start() 37 for x in range(5): 38 t = Consumer() 39 t.start() 40 41 if __name__ == '__main__': 42 main()