本案例模拟一个简单的银行系统,使用两个不同的线程向同一个账户存钱。 账户的初始余额是1000元,两个线程每次存储100元,分别各存储1000元,不允许出现错误数据。
时间: 2024-02-21 13:01:51 浏览: 20
好的,针对您的问题,我们可以使用Python中的Thread和Lock来实现。
代码如下:
```python
import threading
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def deposit(self, amount):
with self.lock:
self.balance += amount
def withdraw(self, amount):
with self.lock:
if self.balance >= amount:
self.balance -= amount
return True
else:
return False
def main():
account = BankAccount(1000)
def deposit_money():
for i in range(10):
account.deposit(100)
print(f"Deposited 100 yuan, current balance: {account.balance}")
threads = []
for i in range(2):
t = threading.Thread(target=deposit_money)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"Final balance: {account.balance}")
if __name__ == '__main__':
main()
```
在这个例子中,我们先定义了一个BankAccount类,它有一个初始余额和一个锁。我们使用锁来确保每个线程都能安全地访问和修改账户余额。
然后我们定义了一个deposit_money函数,它会向账户存储100元,我们创建了2个线程来调用这个函数。每个线程都会执行10次存款操作。
最后,在主函数中,我们等待所有线程执行完毕后,输出最终的账户余额。
这样就可以保证两个线程同时存储1000元,不会出现错误数据。