我正在尝试制作一个简单的线程,将内容附加到全局列表中,然后在睡眠几秒钟后在主线程中打印结果:
import time,threading
list_of_things = []
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def __run__(self):
global list_of_things
for i in range(0, 10):
list_of_things.append('hello ' + str(i))
if __name__ == "__main__":
mythread = MyThread()
mythread.start()
time.sleep(5)
print list_of_things
这个列表显然是空的,尽管我在线程中声明了它是全局的。
将__run__
方法重命名为run
。而且,您不应该调用time.sleep(5)
,而应该在线程上调用.join()
,以使程序等待线程完成其工作。
import threading
list_of_things = []
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global list_of_things
for i in range(0, 10):
list_of_things.append('hello ' + str(i))
if __name__ == "__main__":
mythread = MyThread()
mythread.start()
mythread.join()
print list_of_things