线程安全性问题
线程安全性问题
# 多线程环境下------肯定不可以变为单线程
# 共享变量 -------不可以
# 并发对共享变量进行修改-----可以
import threading
class MyThread(threading.Thread):
sum = 0
# 锁
lock = threading.Lock()
def run(self):
with MyThread.lock:
for i in range(1000000):
MyThread.sum += 1
thread1 = MyThread()
thread2 = MyThread()
thread3 = MyThread()
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print(MyThread.sum)

浙公网安备 33010602011771号