设计一个ATM机,通过多线程完成存款和取款,程序中至少存三笔钱,取两笔钱。
时间: 2024-03-20 14:41:01 浏览: 17
好的,我可以给您提供一个基本的ATM机程序,让您通过多线程完成存款和取款的功能。但是由于我是一个语言模型AI,并没有编程能力,我只能通过文字描述来实现您的需求。以下是程序的基本思路:
1. 定义银行账户类(Account),包含账户余额(balance)和线程锁(lock)属性,以及存款(deposit)和取款(withdraw)方法。
2. 定义存款线程类(DepositThread)和取款线程类(WithdrawThread),分别继承自Thread类,并重写run方法,其中run方法中调用账户类的存款和取款方法。
3. 在主函数中创建账户对象,并创建多个存款线程和取款线程对象,启动这些线程并等待它们全部执行完毕后输出账户余额。
下面是示例代码:
```python
import threading
class Account:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def deposit(self, amount):
with self.lock:
self.balance += amount
print("Deposit %d, balance %d" % (amount, self.balance))
def withdraw(self, amount):
with self.lock:
if amount <= self.balance:
self.balance -= amount
print("Withdraw %d, balance %d" % (amount, self.balance))
return True
else:
print("Withdraw %d failed, balance %d" % (amount, self.balance))
return False
class DepositThread(threading.Thread):
def __init__(self, account, amount):
threading.Thread.__init__(self)
self.account = account
self.amount = amount
def run(self):
self.account.deposit(self.amount)
class WithdrawThread(threading.Thread):
def __init__(self, account, amount):
threading.Thread.__init__(self)
self.account = account
self.amount = amount
def run(self):
self.account.withdraw(self.amount)
def main():
account = Account(1000)
threads = []
for i in range(3):
threads.append(DepositThread(account, 100))
for i in range(2):
threads.append(WithdrawThread(account, 200))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print("Final balance is %d" % account.balance)
if __name__ == '__main__':
main()
```
在这个示例代码中,我们创建了一个初始余额为1000的账户对象。然后创建3个存款线程和2个取款线程,并启动这些线程。最后等待所有线程执行完毕后输出账户余额。注意,在账户类中使用了线程锁来保证存款和取款的原子性和线程安全性。