Python线程疑问:调用join()后VSCode仍显示线程处于Running状态
问题分析:线程调用
join()后VSCode仍显示Running的原因 首先我们先把你的代码格式化,方便后续分析:
import sys, threading def do(): print("Execute") def run(): def start_thread(): thread = threading.Thread(target=do) thread.start() thread.join() return thread t1 = start_thread() t2 = start_thread() run() print('Press enter to Quit') sys.stdin.readline()
先理清你的代码执行逻辑
首先要明确:你的两个线程并不是并行执行的。在start_thread()函数里,你创建线程后立刻调用了thread.join()——这会让当前执行start_thread()的线程(也就是主线程,因为run()是主线程调用的)阻塞等待这个子线程完全执行完毕,才会继续往下走。
实际执行流程是:
- 调用
run(),进入start_thread()创建t1线程并启动 - 主线程等待
t1的do()执行完成(打印"Execute"),t1线程正式结束 - 才会创建
t2线程并启动,主线程再次等待t2执行完成 - 最后
run()执行完毕,回到主线程打印提示并等待输入
也就是说,你的两个线程是串行执行的,同一时间只有一个子线程在运行,而且它们都已经在run()执行过程中就结束了。
为什么VSCode显示它们还处于Running模式?
这大概率是VSCode调试工具的状态更新延迟或者误报,具体原因可能有这些:
- 你的子线程执行速度极快(只是打印一句话),线程从启动到结束的时间太短,VSCode的线程面板来不及捕获到线程的Terminated状态,就停留在了Running的显示上。
- 线程对象
t1和t2虽然超出了run()的作用域,但Python的垃圾回收机制不会立刻销毁这些对象,VSCode可能误把线程对象的存在当成了线程仍在运行的状态——但实际上操作系统层面的线程已经结束了。
如何验证线程确实已经结束?
你可以修改代码,手动打印线程的存活状态来确认:
import sys, threading def do(): print(f"Execute from thread: {threading.current_thread().name}") def run(): def start_thread(): thread = threading.Thread(target=do) thread.start() thread.join() # 打印线程状态,确认是否存活 print(f"Thread {thread.name} is alive? {thread.is_alive()}") return thread t1 = start_thread() t2 = start_thread() # 离开start_thread后再次确认 print(f"After run: t1 alive? {t1.is_alive()}, t2 alive? {t2.is_alive()}") run() print('Press enter to Quit') sys.stdin.readline()
运行这段代码,你会看到输出里明确显示线程已经不再存活(is_alive()返回False),这就证明线程确实已经执行完毕,VSCode的显示只是工具层面的小问题。
内容的提问来源于stack exchange,提问作者No1Lives4Ever
相关产品推荐
相关产品推荐

