test2.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import time
  2. from threading import Thread, Lock
  3. class Account(object):
  4. def __init__(self, balance=0):
  5. self._balance = balance
  6. self._lock = Lock()
  7. @property
  8. def balance(self):
  9. return self._balance
  10. def deposit(self, money):
  11. # 当多个线程同时访问一个资源的时候 就有可能因为竞争资源导致资源的状态错误
  12. # 被多个线程访问的资源我们通常称之为临界资源 对临界资源的访问需要加上保护
  13. if money > 0:
  14. self._lock.acquire()
  15. try:
  16. new_balance = self._balance + money
  17. time.sleep(0.01)
  18. self._balance = new_balance
  19. finally:
  20. self._lock.release()
  21. class AddMoneyThread(Thread):
  22. def __init__(self, account):
  23. super().__init__()
  24. self._account = account
  25. def run(self):
  26. self._account.deposit(1)
  27. def main():
  28. account = Account(1000)
  29. tlist = []
  30. for _ in range(100):
  31. t = AddMoneyThread(account)
  32. tlist.append(t)
  33. t.start()
  34. for t in tlist:
  35. t.join()
  36. print('账户余额: %d元' % account.balance)
  37. if __name__ == '__main__':
  38. main()