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

Python threading脚本运行报错求助:AttributeError与RuntimeError问题

解决你的Python线程脚本错误问题

嘿,我来帮你一步步搞定这两个错误!

第一个错误:AttributeError: 'module' object has no attribute 'Thread'

这个问题的核心是命名冲突:你当前工作目录里大概率有一个叫threading.py(或者编译生成的threading.pyc)的文件。Python导入模块时会优先搜索当前目录,所以你写的import threading实际上导入的是你自己的这个文件,而非Python标准库的threading模块——你自己的文件里当然没有Thread类,自然就报错了。

解决办法:

  • 把你的脚本文件重命名,比如改成threading_demo.py,避开和标准库模块同名
  • 删除目录下的threading.pyc文件(如果存在的话)

第二个错误:RuntimeError: cannot join thread before it is started

这是个很容易犯的小疏忽:你调用线程启动方法时少加了括号!

看你代码里的这一行:

thread.start

start是线程对象的方法,必须加括号thread.start()才能真正执行启动操作。你现在只是引用了这个方法对象,并没有实际启动线程,后面调用thread.join()时,线程根本没开始运行,所以触发了这个错误。

修正后的完整代码

import threading
import time

def myfunction():
    print("Start a thread")
    time.sleep(3)
    print("End a thread")

threads = []
for i in range(5):
    thread = threading.Thread(target=myfunction)
    thread.start()  # 这里补上了括号
    threads.append(thread)

for thread in threads:
    thread.join()

运行修正后的代码,就能正常看到5个线程依次启动,3秒后陆续结束的效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:24:55