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

如何在类的stop()方法中join已启动的thread线程?

如何在stop()方法中调用线程的join()

问题原因

你在run()方法里创建的线程t是局部变量,方法执行结束后变量就会被销毁,stop()方法根本访问不到这个线程对象,自然无法调用join()。

解决方案

把线程对象保存为MyClass的实例属性,这样同一个实例的stop()方法就能直接访问到已启动的线程。

修改后的完整代码:

import threading
import time

mode1=False
mode2=True

stop_thread=False

def function1():
     while True:
        print('function1')
        time.sleep(0.1)  # 加sleep避免打印过于频繁,占用过多CPU
        global stop_thread
        if stop_thread:
            break

def function2():
    while True:
        print('function2')
        time.sleep(0.1)  # 加sleep避免打印过于频繁,占用过多CPU
        global stop_thread
        if stop_thread:
            break

class MyClass():
    def __init__(self):
        self.thread = None  # 初始化线程实例属性,用于存储创建的线程对象

    def run(self):
        if mode1:
            self.thread = threading.Thread(target=function1, daemon=True)
            self.thread.start()
        elif mode2:
            self.thread = threading.Thread(target=function2, daemon=True)
            self.thread.start()

    def stop(self):
        global stop_thread
        stop_thread=True
        if self.thread is not None:  # 先确认线程已创建
            self.thread.join()
            print("线程已正常结束")

v=MyClass()
v.run()
time.sleep(1)  # 让线程运行一段时间再执行停止操作
v.stop()

关键改动说明

  1. 在MyClass的__init__方法中新增self.thread = None,用于存储后续创建的线程对象
  2. run()方法中不再使用局部变量t,而是直接将线程对象赋值给self.thread
  3. stop()方法中先判断self.thread是否存在,再调用join()等待线程结束

额外优化建议

  • 可以把全局变量stop_thread改成MyClass的实例属性,避免全局变量带来的耦合问题,代码结构会更清晰
  • 线程循环里一定要加time.sleep(),否则无间隔的循环会持续占用大量CPU资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:37:20