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

线程执行完毕后,threading.activeCount()仍显示1个活跃线程,无法输出Completed

解决线程执行完毕后无法打印"Completed"的问题

Hey, I see exactly what's going on here! Let's break down the issue and fix it step by step:

问题根源

threading.activeCount() 会把主线程本身也算作活跃线程。当你所有自定义的mythread线程执行完毕后,主线程还卡在那个while循环里跑着呢,所以activeCount()永远不会等于0,自然跳不出循环,也就打不出"Completed"。

解决方案1:使用join()(最推荐)

等待线程结束最简洁高效的方式是用join()方法,它会让主线程阻塞,直到指定的子线程完全执行完毕。修改后的代码如下:

import threading
import sys

class mythread (threading.Thread) :
    def __init__(self,thread_id,argument) :
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.argument = argument
    def run(self) :
        for i in range(5) :
            print(self.thread_id,self.argument)

try :
    thread1 = mythread("T1","arg1")
    thread2 = mythread("T2","arg2")
    thread3 = mythread("T3","arg3")
    
    thread1.start()
    thread2.start()
    thread3.start()
    
    # 等待每个子线程执行完毕后,主线程再继续
    thread1.join()
    thread2.join()
    thread3.join()
    
    print("Completed")
except :
    print("Cannot start the thread")

解决方案2:调整activeCount()的判断条件

如果你坚持想用轮询的方式,那得把判断条件改成检查活跃线程数是否大于1(因为主线程永远是活跃的):

# 替换你原来的while循环
while threading.activeCount() > 1 :
    pass

注意:这种方式不太推荐,因为轮询会浪费CPU资源,而且如果程序里还有其他后台线程在运行,这个逻辑会失效。

为什么join()是更好的选择

  • 这是Python里等待线程结束的标准、惯用写法
  • 不会像轮询那样无意义地消耗CPU
  • 代码可读性和可维护性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:37:56