Python线程技术问题:并行While True循环无法同时启动双线程
问题根源:
join()方法的误用 哦,我一眼就看穿问题所在啦!你代码里的thread1.join()是罪魁祸首——join()方法的作用是让当前执行的线程(这里是主线程)暂停下来,一直等待目标子线程完全执行完毕,才会继续往下执行后续代码。
但你的haha_function是个while True的无限循环,永远不会结束,所以主线程会一直卡在thread1.join()这里,根本没机会去创建和启动thread2!这就是为什么你只能看到"Haha"输出,完全看不到"Coffee"的原因。
修正方案:调整
join()的位置(或按需取舍) 你需要先把两个线程都启动起来,再考虑是否需要让主线程等待它们(不过因为是无限循环,其实join会让主线程也卡住,除非你有线程停止的逻辑)。
修改后的代码示例:
import threading import time # 请根据你的实际情况导入Screen类 from your_module import Screen def haha_function(): while True: print("Haha") time.sleep(0.5) def coffee_function(): while True: print("Coffee") time.sleep(0.5) class DummyScreen3(Screen, threading.Thread): def do_something(self): # 先初始化两个线程 thread1 = threading.Thread(target=haha_function, daemon=True) thread2 = threading.Thread(target=coffee_function, daemon=True) # 先启动所有子线程 thread1.start() thread2.start() # 注意:如果你的主线程需要保持存活(比如GUI程序),这里不需要join # 因为daemon=True的线程会在主线程结束时自动终止 # 如果是普通脚本,想让主线程不退出,可以加个简单的循环: # while True: # time.sleep(1)
这样修改后,两个线程会同时启动,你就能看到"Haha"和"Coffee"交替输出啦!
额外提示
如果之后你需要优雅地停止这两个无限循环线程,可以考虑用threading.Event()来做信号控制,比如给每个函数加一个停止参数:
def haha_function(stop_event): while not stop_event.is_set(): print("Haha") time.sleep(0.5) # 在do_something里: stop_event = threading.Event() thread1 = threading.Thread(target=haha_function, args=(stop_event,), daemon=True) # 之后需要停止时调用stop_event.set()
内容的提问来源于stack exchange,提问作者Jacob Gravesen
相关产品推荐
相关产品推荐

