1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| """ 线程之间的通信 condition acquire wait notify notifyAll 方法 """ import threading
class Account:
def __init__(self, account_no, balance): self.account_no = account_no self.__balance = balance self.cond = threading.Condition() self.__flag = False
def getBalance(self): return self.__balance
def draw(self, draw_amount): self.cond.acquire() try: if not self.__flag: self.cond.wait() else: print(threading.current_thread().getName() + '取钱:' + str(draw_amount)) self.__balance -= draw_amount print('余额为:' + str(self.__balance)) self.__flag = False self.cond.notifyAll() finally: self.cond.release()
def deposit(self, deposit_amount): self.cond.acquire() try: if self.__flag: self.cond.wait() else: print(threading.current_thread().getName() + '存钱:' + str(deposit_amount)) self.__balance += deposit_amount print('账户余额为:' + str(self.__balance)) self.__flag = True self.cond.notifyAll() finally: self.cond.release()
def draw_money(account, draw_amount, max): for i in range(max): account.draw(draw_amount)
def deposit_money(account, deposit_amount, max): for i in range(max): account.deposit(deposit_amount)
acct = Account('123456', 0) threading.Thread(target=draw_money, args=(acct, 800, 60), name='张三').start() threading.Thread(target=deposit_money, args=( acct, 800, 20), name='存钱甲').start() threading.Thread(target=deposit_money, args=( acct, 800, 20), name='存钱乙').start() threading.Thread(target=deposit_money, args=( acct, 800, 20), name='存钱丙').start()
|