更新:
好的,所以您想知道更多关于如何让display1.py打印结果的信息。如果你能解释为什么这很重要,那会很有帮助,因为这可能会改变你应该怎么做,但这里有一个第一种方法:# threads1.py
from threading import Thread
import time
class ThreadManager:
def __init__(self):
self.threads = {}
def start(self):
t1 = MyThread(4)
t1.daemon = True
t1.start()
self.threads[1] = t1
t2 = MyThread(1)
t2.daemon = True
t2.start()
self.threads[2] = t2
def is_alive(self, thread_id):
return self.threads[thread_id].is_alive()
def GetResults(self): # or you could just access results directly
return self.results
class MyThread(Thread):
def __init__(self, SleepWait):
Thread.__init__(self)
self.SleepWait = SleepWait
def run(self):
time.sleep(self.SleepWait)
然后。。。在
^{pr2}$
您最终应该考虑使用Crast建议的队列;但是让我们先关注一下如何正确使用它。在
原帖:
此代码存在许多问题。在
首先,应该使用t1.is_alive()检查线程是否完成。不需要用AskFinished重新实现它。在
第二,threads1.py中的while True:循环在等待线程终止时以的速度不做任何事情。如果你不相信我的话,看看这个运行时的cpu使用情况。您应该在那里抛出一个time.sleep(1)语句。在
第三,为什么要使用全局var来返回结果?这真是件奇怪的事。把它存起来就行了!在
最后,为什么display1.py必须打印消息?为什么thread1.py不能这样做?在
考虑到这四点,这里有一个thread1.py,它的作用更为合理:from threading import Thread
import time
class ThreadManager:
def __init__(self):
self.results = None
def start(self, answer): # why is "answer" here?
self.answer = answer
thread_refs = []
t1 = MyThread(4, 'Not finished')
t1.daemon = True
t1.start()
t2 = MyThread(1, 'Not finished')
t2.daemon = True
t2.start()
t1_state = t2_state = True
while t1.is_alive() or t2.is_alive():
time.sleep(1)
if t1.is_alive() != t1_state:
print("t1 finished")
t1_state = t1.is_alive()
if t2.is_alive() != t2_state:
print("t2 finished")
t2_state = t2.is_alive()
if not t1.is_alive() and not t2.is_alive():
self.results = [t1.AskFinished, t2.AskFinished]
print("Both Finished")
break
def GetResults(self): # or you could just access results directly
return self.results
class MyThread(Thread):
def __init__(self, SleepWait, AskFinished):
Thread.__init__(self)
self.SleepWait = SleepWait
self.AskFinished = AskFinished
def run(self):
time.sleep(self.SleepWait)
self.AskFinished = 'Finished'
现在,这仍然不能完全满足您的需要,因为您要求display.py来显示。要实现这一点,您必须将while True循环放入display.py,并添加一个ThreadManager.is_alive()方法,display.py可以用来检查线程是否处于活动状态。如果你想知道怎么做,让我知道。在