【发布时间】:2019-09-13 15:36:11
【问题描述】:
我到处看了看,似乎我写的线程应该可以工作。我已经检查了许多关于它和教程的其他线程。我似乎无法在线程中运行无限循环。尽管我做了什么,只有第一个线程工作/打印。
这是方法的代码。
import threading
def thread1():
while True:
print("abc")
def thread2():
while True:
print ("123")
if __name__ == "__main__":
t1 = threading.Thread(target=thread1())
t2 = threading.Thread(target=thread2())
t1.start
t2.start
t1.join
t2.join
在使用target=调用函数结束时删除前缀不会打印任何内容,因此我将其保留在那里。
这是类/对象版本。
from threading import Thread
class Thread1(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start
def run():
while True:
print ("abc")
class Thread2(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start
def run():
while True:
print ("123")
Thread1.run()
Thread2.run()
两者都无法打印123,我不知道为什么。看起来无限循环应该不是问题,因为它们是并行运行的。我尝试了time.sleep(可能是 GIL 停止了它 idk),所以 thread2 可以在 thread1 空闲时运行。没用。
【问题讨论】:
标签: python multithreading python-multithreading