import threading
x = 0;
class Thread1(threading.Thread):
def run(self):
global x
for i in range(1,100000):
x = x + 1
class Thread2(threading.Thread):
def run(self):
global x
for i in range(1,100000):
x = x - 1
#create two threads
t1 = Thread1()
t2 = Thread2()
#start the threads
t1.start()
t2.start()
#wait for the threads to finish
t1.join()
t2.join()
print x;
多次运行会产生不同的输出,有些是负面的,有些是正面的。是因为这两个线程使用的是同一个全局 x 吗?我不明白为什么:尘埃落定后,净效应(输出)不应该相同吗?