温馨提示×

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

小亿
114
2024-01-22 09:24:59
栏目: 编程语言

在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,从而停止线程的执行。

0