1 importación roscado 2 importación tiempo 3 importación azar 4 5 6 gmoney = 1,000 7 gCondition = threading.Condition () 8 gtime = 0 9 10 clase Productor (threading.Thread): 11 def ejecutar (self): 12 mundial gmoney 13 mundial gtime 14 , mientras que 1 : 15 dinero = random.randint (100,1000 ) 16 si gtime <= 9 : 17 gCondition.acquire () 18 gmoney + = dinero 19 de impresión ( ' % s生产了% d,账户总余额% d ' % (threading.current_thread (), dinero, gmoney)) 20 gCondition.notify_all () 21 gCondition.release () 22 gtime + = 1 23 otra cosa : 24 descanso 25 time.sleep (0,5 ) 26 27 28 clase Consumidor (threading.Thread): 29 def ejecutar (self): 30 mundial gmoney 31 mundial gtime 32 mientras que 1 : 33 dinero = random.randint (100,1000 ) 34 gCondition.acquire () 35 mientras gmoney < dinero: 36 si gtime> = 10 : 37 gCondition.release () 38 de retorno 39 gCondition.wait ( ) 40 gmoney - = dinero 41 de impresión ( ' % s消费了% d,账户余额% d ' % (threading.current_thread (), dinero, gmoney)) 42 gCondition.release () 43 time.sleep (0,5 ) 44 45 def main (): 46 para x en rango (5 ): 47 t = Productor () 48 t.Start () 49 para x en rango (5 ): 50 t = Consumidor () 51 t.Start () 52 53 si __name__ == ' __main__ ' : 54 main ()