boolean
更新为True?我在全球范围内定义了它。
import threading
import time
boolean = False
class ThreadClass(threading.Thread):
def __init__(self):
global boolean
super(ThreadClass, self).__init__()
def run(self):
global boolean
for i in range(6):
print str(i)
time.sleep(1)
t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'
0
1
2
end script
3
4
5
答案 0 :(得分:2)
将print str(i)
更改为print str(i), boolean
,您会发现它确实发生了变化:
:: python so-python-thread.py
0 False
1 False
2 False
end script
3 True
4 True
5 True
这是我的代码版本:
import threading
import time
boolean = False
class ThreadClass(threading.Thread):
def __init__(self):
super(ThreadClass, self).__init__()
def run(self):
global boolean
for i in range(6):
print str(i), boolean
time.sleep(1)
t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'
你确实有一个小错误:
t = ThreadClass().start()
start()
方法返回None
,因此t
将为None
。您需要单独实例化线程,然后启动它。另外,我明确地等待线程加入:
import threading
import time
boolean = False
class ThreadClass(threading.Thread):
def __init__(self):
super(ThreadClass, self).__init__()
def run(self):
global boolean
for i in range(6):
print str(i), boolean
time.sleep(1)
t = ThreadClass()
t.start()
time.sleep(3)
boolean = True
t.join()
print 'end script'