解决数据共享引起操作混乱问题,就必须给当前操作数据的线程加一把锁:
1.实例化锁
2.获取锁
3.释放锁
import time,threading balance=0 # 实例化锁,一个进程,同一时刻只能拥有1把锁 lock=threading.Lock() def change_it(n): global balance balance=balance+n+20 balance=balance-n def run_thread(n): for i in range(100): # 先要获取锁: lock.acquire() try: change_it(n) finally: # 改完了一定要释放锁: lock.release() # 开启两个线程,每个线程调用 run_thread(n)又随机分配多个任务 t1=threading.Thread(target=run_thread,args=(5,)) t2=threading.Thread(target=run_thread,args=(8,)) t1.start() t2.start() t1.join() t2.join() print('两个线程运行完毕') print('打印最终存款:',balance)