0
我开始编写一个使用线程的程序,但在搜索如何在Python中启动线程之后,我发现了两种方法可以实现相同的功能。彼此之间必定有差异或优势。困惑我应该走下哪条路。多线程类vs方法
我的线程将持续在后台运行,并且不会停止,直到程序被用户告知为止。另外一个或多个参数将在启动时传递给线程。
一个使用方法类:
from threading import Thread
class myClassA(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start()
def run(self):
while True:
print 'A'
myClassA()
while True:
pass
其次使用的方式方法:
from threading import Thread
def runA():
while True:
print 'A\n'
if __name__ == "__main__":
t1 = Thread(target = runA)
t1.setDaemon(True)
t1.start()
while True:
pass
你应该在你的最后一个例子中使用't1.daemon = True'。在选择调用'__init __(。)中的.start()'之前,请确保您了解https://docs.python.org/2/library/threading.html#importing-in-threaded-code中提到的导入限制。 )全局对象的方法... – thebjorn