- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlock_thread.py
More file actions
Latest commit
25 lines (22 loc) · 778 Bytes
/
Copy pathlock_thread.py
File metadata and controls
25 lines (22 loc) · 778 Bytes
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
importtime
importthreading
lock=threading.Lock()
classAccount:
def__init__(self, balance):
self.balance=balance
defdraw_money(account, amount):
# 使用with lock包裹代码
withlock:
ifaccount.balance>=amount:
# time.sleep(1)
print(threading.current_thread().name, '取钱成功')
account.balance-=amount
print(threading.current_thread().name, "余额", account.balance)
else:
print(threading.current_thread().name, '取消失败,余额不足')
if__name__=='__main__':
account=Account(1000)
t1=threading.Thread(target=draw_money, args=(account, 600))
t2=threading.Thread(target=draw_money, args=(account, 600))
t1.start()
t2.start()