#!/usr/local/bin/python3
# coding=utf-8
import threading
class Account:
def __init__(self, card_id, balance):
self.card_id = card_id
self._balance = balance
self.cond = threading.Condition()
self._flag = False
# 取钱
def draw(self, balance):
self.cond.acquire() # 加绑定锁
try:
if not self._flag:
self.cond.wait()
else:
self._balance -= balance
self._flag = False
print("{}取钱成功{}元,余额{}元。".format(threading.current_thread().name, balance, self._balance))
self.cond.notify_all()
except:
print("未知错误!")
finally:
self.cond.release() # 释放绑定的锁
# 存钱
def deposit(self, balance):
self.cond.acquire() # 加绑定锁
try:
if self._flag:
self.cond.wait()
else:
self._balance += balance
self._flag = True
print("{}存钱成功{}元,余额{}元。".format(threading.current_thread().name, balance, self._balance))
self.cond.notify_all()
except:
print("未知错误!")
finally:
self.cond.release() # 释放绑定的锁
# 取钱多次
def draw_many(account, balance, n):
for i in range(n):
account.draw(balance)
print("取钱第{}次".format(i + 1))
# 存钱多次
def deposit_many(account, balance, n):
for i in range(n):
account.deposit(balance)
# print("存钱第{}次".format(i + 1))
if __name__ == "__main__":
account = Account("110", 0)
# 存钱线程
thread1 = threading.Thread(name="甲", target=deposit_many, args=(account, 800, 100))
# 取钱线程
thread2 = threading.Thread(name="乙", target=draw_many, args=(account, 800, 100))
thread1.start()
thread2.start()