python中怎么用threading.Thread停止线程
在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
,从而停止线程的执行。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:php中usort函数的作用是什么 下一篇:虚拟主机怎么建立数据库
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。