1 importation filetage 2 import temps 3 import aléatoire 4 5 6 Gmoney = 1000 7 Glock = threading.Lock () 8 9 classe Producteur (threading.Thread): 10 def exécuter (self): 11 global Gmoney 12 tandis que 1 : 13 d' argent = random.randint (100,1000 ) 14 gLock.acquire () 15 Gmoney + = argent 16 impression ( '% s% d生产了,账户总余额% d ' % (threading.current_thread (), de l' argent, Gmoney)) 17 gLock.release () 18 time.sleep (0,5 ) 19 20 21 classe des consommateurs (threading.Thread): 22 def course (auto): 23 global Gmoney 24 en 1 : 25 argent = random.randint (100,1000 ) 26 si Gmoney> = argent: 27 gLock.acquire () 28 Gmoney - = argent 29 impression (' % S消费了% d,% d账户余额' % (threading.current_thread (), de l' argent, Gmoney)) 30 gLock.release () 31 time.sleep (0,5 ) 32 33 def main (): 34 pour x dans plage (5 ): 35 t = Producteur () 36 t.start () 37 pour x en éventail (5 ): 38 t = consommation () 39 t.start () 40 41 si __name__ == '__main__': 42 main()