模拟银行取款 初始金额1000元 两个线程为取款用户,取款200,300,并在屏幕输出两个线程为存款用户,存款100,400,并在屏幕输出·线程结束后,显示余额 Python实现
时间: 2024-10-25 13:09:29 浏览: 23
在Python中,我们可以使用`threading`模块来模拟并发的银行取款和存款操作。这里是一个简单的例子,我们将使用锁(`Lock`)来保证线程安全,因为多个线程同时访问同一资源可能导致数据竞争:
```python
import threading
# 初始余额
balance = 1000
lock = threading.Lock()
class AccountOperation:
def __init__(self, operation, amount):
self.operation = operation
self.amount = amount
def execute(self):
global balance
lock.acquire() # 获取锁
try:
if self.operation == 'withdraw':
balance -= self.amount
print(f"Thread {threading.current_thread().name} is a withdraw user, withdrawing {self.amount}, new balance: {balance}")
elif self.operation == 'deposit':
balance += self.amount
print(f"Thread {threading.current_thread().name} is a deposit user, depositing {self.amount}, new balance: {balance}")
finally:
lock.release() # 无论操作成功与否都会释放锁
# 创建取款和存款任务
withdraw_task1 = AccountOperation('withdraw', 200)
deposit_task1 = AccountOperation('deposit', 100)
withdraw_task2 = AccountOperation('withdraw', 300)
deposit_task2 = AccountOperation('deposit', 400)
# 启动线程
threads = [threading.Thread(target=task.execute) for task in [withdraw_task1, withdraw_task2, deposit_task1, deposit_task2]]
for t in threads:
t.start()
for t in threads:
t.join() # 等待所有线程完成
print("All operations completed, final balance:", balance)
阅读全文