-
创建一个代表银行的账户对象,启动100个线程,每个线程向该账户存入1元,最后查询总额
""" 例如:创建一个代表银行的账户对象,启动100个线程, 每个线程向该账户存入1元,最后查询总额 """ from threading import Thread, Lock from time import sleep class Account: def __init__(self): self.balance = 0.0 self.lock = Lock() def deposit(self, money): with self.lock: new_balance = self.balance + money sleep(0.001) self.balance = new_balance def main(): account = Account() threads = [] for _ in range(100): t = Thread(target=account.deposit, args=(1, )) t.start() threads.append(t) for t in threads: t.join() print(f'总金额为:{account.balance}') if __name__ == '__main__': main()
Python常见编程题2
最新推荐文章于 2024-07-10 17:50:46 发布