from threading import Thread, Lock
class Customer:
def __init__(self):
self._money = 0
#锁
self._lock = Lock()
def deposit(self, money):#账户获得汇款
#获取锁
self._lock.acquire()
new_money = self._money + money
time.sleep(0.01)
self._money = new_money
#释放锁
self._lock.release()
class AddMoneyThread(Thread):
def __init__(self, cus, money):
Thread.__init__(self)
self._customer = cus
self._money = money
def run(self):#给账户汇款
self._customer.deposit(self._money)
def main_3():
customer = Customer()
threads = []
for _ in range(100):
thread = AddMoneyThread(customer, random.random())
threads.append(thread)
thread.start()
for t in threads:
t.join()
print('一共存了{:.3f}钱!'.format(customer._money))
if __name__ == "__main__":
main_3()
pass