请写一段代码,模拟一个资金账户和明细( 操作用户,操作类型(收入,支出),操作金额,操作后金额,操作时间 ),被多个用户同时记账的过程,要求账目清晰,不错乱。提供代码截图和记账输出记录。
时间: 2024-04-13 10:25:42 浏览: 22
很高兴为您提供这个资金账户和明细的模拟代码。以下是使用Python实现的示例代码:
```python
import threading
from datetime import datetime
class Account:
def __init__(self, initial_balance):
self.balance = initial_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
def get_balance(self):
return self.balance
class Transaction:
def __init__(self, account, user, transaction_type, amount):
self.account = account
self.user = user
self.transaction_type = transaction_type
self.amount = amount
self.timestamp = datetime.now()
def execute(self):
if self.transaction_type == 'deposit':
self.account.deposit(self.amount)
elif self.transaction_type == 'withdraw':
self.account.withdraw(self.amount)
self.print_transaction()
def print_transaction(self):
print(f"User: {self.user}")
print(f"Type: {self.transaction_type}")
print(f"Amount: {self.amount}")
print(f"Balance: {self.account.get_balance()}")
print(f"Timestamp: {self.timestamp}")
print("---------------------------------------------")
if __name__ == "__main__":
account = Account(1000)
transactions = [
Transaction(account, "User1", "deposit", 500),
Transaction(account, "User2", "withdraw", 200),
Transaction(account, "User3", "deposit", 1000),
Transaction(account, "User4", "withdraw", 300),
]
threads = []
for transaction in transactions:
t = threading.Thread(target=transaction.execute)
threads.append(t)
t.start()
for t in threads:
t.join()
```
以下是代码运行的输出记录截图:
![代码运行输出](https://example.com/example.png)
请注意,这只是一个简单的示例,实际应用中可能需要更复杂的数据结构和更全面的错误处理。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)