You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类中使用threading同时运行多个方法仅单个生效问题求助

问题根因

你的代码存在两个核心错误:

  • 创建线程时target参数传入的是self.testFunc1(),加了括号等于直接同步调用该函数,而testFunc1内部是死循环,执行后程序会卡在此处,根本不会执行后续创建第二个线程的代码
  • 类实例方法已经自动绑定了self上下文,不需要再通过args额外传入self参数,属于无效传参
修复后的完整代码
import time, threading

class testClass:
    def __init__(self):
        self.count = 0

    def testFunc1(self):
        while True:
            print(self.count)
            self.count = self.count + 1
            time.sleep(1)

    def testFunc2(self):
        while True:
            print("test2")
            time.sleep(1)

    def run(self):
        # 仅传方法引用,不加括号,无需额外传args
        threading.Thread(target=self.testFunc1).start()
        threading.Thread(target=self.testFunc2).start()

test = testClass()
test.run()
多线程使用常见注意事项
  • 给Thread的target参数传值时,永远只传函数/方法的引用,不要加括号,加括号会立刻执行函数,不会交给线程调度
  • 只有当你需要给线程执行的函数传递参数时,才需要填写args参数,参数需要打包成元组传入,例如函数需要入参a、b时,写法为args=(a, b)
  • 随主程序生命周期运行的子线程,建议设置daemon=True,这样主程序退出时会自动销毁所有守护线程,避免进程残留,写法为threading.Thread(target=xxx, daemon=True).start()
  • 多个线程需要修改同一个共享变量时,必须加threading.Lock互斥锁,否则会出现数据读写错乱的问题
  • 线程间传递数据优先使用queue.Queue,队列本身是线程安全的,不需要额外加锁就能保证数据读写正确

内容的提问来源于stack exchange,提问作者swagman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:06:03