多线程
# 模拟多线程 import threading num=0 lock=threading.Lock() def change_it(n): global num if lock.acquire(): try: for i in range(1000000): num = num + n num = num - n finally: lock.release() print('释放锁') print(num) th=threading.Thread(target=change_it,args=(8,)) th.start() threass=[ threading.Thread(target=change_it,args=(8,)), # # threading.Thread(target=change_it,args=(10,)), ] # [ t.start() for t in threass ] # [ t.join() for t in threass ] print(num,'9999999999999')
import time from threading import Thread def func(name): print(f"{name}开始") time.sleep(0.5) print(f"{name}结束") if __name__ == '__main__': t1 = Thread(target=func, args=("线程1",)) t2 = Thread(target=func, args=("线程2",)) t1.start() t2.start() print("主线程结束")