Skip to main content
 首页 » 编程设计

python之如何使 threading.Thread start() 调用 run() 以外的方法

2025年05月04日62yyy_WW

我有一个类有两个方法 run()和 run_forever() ,后者反复调用前者。我想跑 run_forever()对于不同线程上的类的不同实例,但到目前为止我还不能偏离 threading.Thread调用 run() 的默认行为.

这是我想要实现的简化版本:

import time 
import threading 
 
class Controller(object): 
    def run(self): 
        print("Running once...") 
 
    def run_forever(self): 
        while True: 
            self.run() 
            time.sleep(1) 
 
class ThreadController(Controller, threading.Thread): 
    def __init__(self, *args, **kwargs): 
        Controller.__init__(self, *args, **kwargs) 
        threading.Thread.__init__(self, target=self.run_forever) 
 
if __name__ == "__main__": 
    thread_controller = ThreadController() 
    thread_controller.start() 
    thread_controller.join() 

如果我运行这个脚本,它会打印出 Running once...一次,并且不会像我预期的那样通过设置 target=self.run_forever 继续每秒打印一次在 threading.Thread 的初始化中.我如何修改此代码以实现所需的行为?

请您参考如下方法:

停止从 Controller 继承:

controller = Controller() 
thread = threading.Thread(target=controller.run_forever)