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

标签 python multithreading

我有一个类有两个方法 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)

关于python - 如何使 threading.Thread start() 调用 run() 以外的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40363986/

相关文章:

java - NioEventLoopGroup 的自定义执行器危险吗?

javafx线程限制为32?

python - 在数据库查询中使用占位符不起作用

Python:转换数据集

python - Python 中 sum() 的时间复杂度是多少?

python - 使用 "pygal.maps.world"绘制世界地图时如何为每个类别设置特定的颜色?

python - sqlalchemy - 多个文件 - 关系

iphone - 互斥锁上的阻塞是否相当于空 while 循环?

java - Web 应用程序的真实世界用户 Activity 日志记录策略

java - ThreadPoolExecutor 的 Thread.join()