python中怎么用threading.Thread停止线程

27次阅读
没有评论

共计 458 个字符,预计需要花费 2 分钟才能阅读完成。

在 Python 中,可以通过设置一个标志位,来停止线程的执行。示例如下:

import threading

class MyThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def run(self):
        while not self._stop_event.is_set():
            # 线程的执行逻辑 
            pass

# 创建并启动线程 
thread = MyThread()
thread.start()

# 停止线程 
thread.stop()

在上述示例中,MyThread 类继承自 threading.Thread 类,并重写了 run 方法作为线程的执行逻辑。在 run 方法中,通过检查标志位 _stop_event 的状态来判断是否继续执行任务。

通过调用 stop 方法,可以设置标志位 _stop_event,从而停止线程的执行。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计458字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)