如何终止Python类方法中运行的无限循环?
问题分析与解决方案
问题原因
你的代码陷入死循环的核心原因是主线程被完全阻塞:
- 创建
Test2实例时,__init__方法直接调用了self.test.test1(),这个方法里的while循环会持续占用主线程,导致后续的print("What is going on?")和test.stop_test()根本没有执行机会。 - 既然修改终止标记
boolean的代码永远跑不到,循环自然会一直持续下去。
修正后的代码
使用Python的threading模块把循环逻辑放到子线程中运行,让主线程能正常执行后续的终止操作:
import time import threading class Test: def __init__(self): self.counter = 0 self.boolean = True def test1(self): while self.boolean: time.sleep(0.5) print(self.counter) self.counter += 1 class Test2: def __init__(self): self.test = Test() # 将循环逻辑放到子线程启动,不阻塞主线程 self.loop_thread = threading.Thread(target=self.test.test1) self.loop_thread.start() def stop_test(self): time.sleep(2) print("Now I change the boolean value") self.test.boolean = False # 等待子线程完全结束 self.loop_thread.join() test = Test2() print("What is going on?") test.stop_test() print("Loop stopped successfully!")
代码说明
- 引入
threading模块后,通过Thread类创建子线程来承载test1的循环逻辑,调用start()启动子线程后,主线程会立刻继续向下执行,不会被循环阻塞。 stop_test方法修改boolean标记后,子线程的循环会在下一次条件判断时退出,最后用join()方法等待子线程完全终止,保证程序执行的完整性。
内容的提问来源于stack exchange,提问作者Mario Kroll
相关产品推荐
相关产品推荐

