多线程经常使用的银行储户同时取钱来作为实例
不加锁的多线程
import time
import threading
class Account():
def __init__(self,account_no, balance):
# 构造函数account_no账户名,blance账户余额
self.account_no=account_no
self.balance=balance
#取钱函数
def drop(account,draw_amount):
if account.balance > draw_amount:
print(threading.current_thread().name+'取款成功,取出:'+str(draw_amount))
time.sleep(2)
account.balance -= draw_amount
print('账户余额为:'+str(account.balance))
else:
print(str(account.account_no)+'余额不足')
a=Account('12345',1000)
threading.Thread(name="甲",target=drop,args=(a,800)).start()
threading.Thread(name="乙",target=drop,args=(a,800)).start()
因为没有锁,用户的存款会多次成为负数
加锁以后
import threading, time
# 导入线程模块 ,不加锁的话就会造成用户的存款变为负数~
class Account():
def __init__(self, accoun_no, balance):
self.accoun_no = accoun_no # 模拟卡号
self.balance = balance # 模拟存数数额
self.lock = threading.RLock() # 加锁变量
def get_Balance(self):
return self.balance # 得到余额
def draw(self, draw_amount): # 取钱方法 draw_amount 取钱的数量
self.lock.acquire() # 上锁
try: # 异常
if draw_amount < self.balance:
# threading.current_thread().name获取进程的名字
print(threading.current_thread().name + '取钱成功,取出:' + str(draw_amount))
time.sleep(1.5)
self.balance -= draw_amount
print('账户余额为:' + str(self.balance))
else:
print(threading.current_thread().name + '取钱失败,账户余额不足!')
finally:
self.lock.release() # 解锁
def draw(account, draw_amount): # 定义一个取钱的函数 account储户的实例 draw取钱的金额
account.draw(draw_amount) # 使用储户实例的draw方法
if __name__ == '__main__':
a1 = Account('123456', 1000) # 生成一个储户实例
threading.Thread(name="甲", target=draw, args=(a1, 800)).start() # 用户甲使用储户a1账户取钱
# name=给进程取的名称,ainThread为主线程
threading.Thread(name='乙', target=draw, args=(a1, 800)).start() # 用户乙同时使用储户a1账户取钱